Extension Methods
Oftentimes you’ll find yourself using classes you can’t modify. Whether they’re basic data types or part of an existing framework, you’re stuck with the functions that are provided. That being said, C# provides a nifty trick to appending functions to classes! These are known as Extension Methods.
Extension methods are fairly simple to create and are frequently used as syntactic sugar. A practical example can be seen with Unity’s Transform class. Let’s say you want to set only the x variable of Transform.position.
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { void Update () { //Set new x position to 5 transform.position = new Vector3(5f, transform.position.y, transform.position.z); } } |
In this case Transform.position gives you an error if you only try to assign its x member variable, so you have to assign the entire Vector3. An extension method such as SetPositionX() could be appended to the Transform class and help make this code more readable.
In order to create extension methods you have to create a static class. In addition, an extension method declaration must be declared static and have the first parameter be of the type that you’re writing the method for, preceded by the this keyword.
using UnityEngine; using System.Collections; //Must be in a static class public static class Extensions { //Function must be static //First parameter has "this" in front of type public static void SetPositionX( this Transform t, float newX) { t.position = new Vector3(newX, t.position.y, t.position.z); } } |
Now you can go back to your other script and replace our old code with the new extension method.
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { void Update () { //Set new x position to 5 transform.SetPositionX(5f); } } |
Here are a few more extension methods to get you started, as well as an example script that utilizes a few of them.
Extensions:
using UnityEngine; using System.Collections; public static class Extensions { public static void SetPositionX( this Transform t, float newX) { t.position = new Vector3(newX, t.position.y, t.position.z); } public static void SetPositionY( this Transform t, float newY) { t.position = new Vector3(t.position.x, newY, t.position.z); } public static void SetPositionZ( this Transform t, float newZ) { t.position = new Vector3(t.position.x, t.position.y, newZ); } public static float GetPositionX( this Transform t) { return t.position.x; } public static float GetPositionY( this Transform t) { return t.position.y; } public static float GetPositionZ( this Transform t) { return t.position.z; } public static bool HasRigidbody( this GameObject gobj) { return (gobj.rigidbody != null ); } public static bool HasAnimation( this GameObject gobj) { return (gobj.animation != null ); } public static void SetSpeed( this Animation anim, float newSpeed) { anim[anim.clip.name].speed = newSpeed; } } |
Example Script:
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { void Update () { //move x position 5 units float currentX = transform.GetPositionX(); transform.SetPositionX(currentX + 5f); if (gameObject.HasRigidbody()) { //Do something with physics! } if (gameObject.HasAnimation()) { //Double the animation speed! gameObject.animation.SetSpeed(2f); } } } |
Extension Methods的更多相关文章
- C# Extension Methods
In C#, extension methods enable you to add methods to existing class without creating a new derived ...
- AX7: HOW TO USE CLASS EXTENSION METHODS
AX7: HOW TO USE CLASS EXTENSION METHODS To create new methods on a standard AX class without custo ...
- C# -- 扩展方法的应用(Extension Methods)
当你有下面这样一个需求的时候,扩展方法就会起到作用:在项目中,类A需要添加功能,我们想到的就是在类A中添加公共方法,这个显而易见肯定可以,但是由于某种原因,你不能修改类A本身的代码,但是确实又需要增加 ...
- Top useful .Net extension methods
Special extension methods were released in C# 3.0. Developers have continuously been looking for way ...
- (转)C# -- 扩展方法的应用(Extension Methods)
本文转载自:http://blog.csdn.net/zxz414644665/article/details/9793205 当你有下面这样一个需求的时候,扩展方法就会起到作用:在项目中,类A需要添 ...
- Extension Methods "点"函数方法 扩展方法
原文发布时间为:2011-03-25 -- 来源于本人的百度文章 [由搬家工具导入] http://msdn.microsoft.com/en-us/library/bb383977.aspx 条件: ...
- Extension Methods(扩展方法)
在 OOPL 中,有静态方法.实例方法和虚方法,如下: public sealed class String { public static bool IsNullOrEmpty(st ...
- Extension Methods (C# Programming Guide)
https://msdn.microsoft.com/en-us//library/bb383977.aspx private static void Dump(this ArraySegment&l ...
- C# Extension Methods(C#类方法扩展)
使用Extension methods 可以在已有的类型(types)中添加方法(Methods),而无需通过增加一种新的类型或修改已有的类型. 比如说,想要给string类型增加一个PrintStr ...
随机推荐
- GDAL Configure in Visual Studio 2010 for Win7/ GDAL+VisualStudio2010 Win7 配置
配置环境: OS:Win& *86 Ultimate Edition(EN) VS:Visual Studio 2010(EN) Step1: GDAL源码下载:http://www.gisi ...
- JS判断客户端是手机还是PC
function IsPC() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", " ...
- 用CSS实现Firefox 和IE 都支持的Alpha透明效果
有的时候,为了实现一些特殊效果,需要将页面元素变透明,本文介绍的就是用 CSS 实现 Firefox 和 IE 都支持的 Alpha 透明效果.CSS: filter:alpha(opacity=50 ...
- CentOS6.4安装LAMP环境
1.配置防火墙,开放80.3306端口 vi /etc/sysconfig/iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport - ...
- 联想预装win8系统改成win7操作步骤及注意事项
联想消费台式机与一体机预装Windows8改装Windows7的操作步骤及常见问题 前提说明: 目前联想出厂预装Windows 8的台式和一体机使用都是UEFI+GPT硬盘的组合,并且开启了安全启动, ...
- 【Qt】Qt之进程间通信(共享内存)【转】
简述 上一节中,我们分享下如何利用Windows消息机制来进行不同进程间的通信.但是有很多局限性,比如:不能跨平台,而且必须两个进程同时存在才可以,要么进程A发了消息谁接收呢? 下面我们来分享另外一种 ...
- arguments.callee 调用函数自身用法----JSON.parse()和JSON.stringify()前端js数据转换json格式
arguments.callee 调用函数自身用法 arguments.callee 在哪一个函数中运行,它就代表哪个函数. 一般用在匿名函数中. 在匿名函数中有时会需要自己调用自己,但是由于是匿名函 ...
- 封装鼠标滚轮事件_mousewheel
function mousewheel(obj,fn){ obj.onmousewheel===null ? obj.onmousewheel=fun : obj.addEventListener(' ...
- PHP学习之数组的定义和填充
数组就是把一组数据按顺序放在一起.PHP的数组和其它的语言数组有一点点不同:第一,保存的数据是可以是任何类型的:第二,数组的索引可以是数字,也可以是字符串. PHP的数组,说白了,就是关联数据每一条数 ...
- opencv初体验
http://guoming.me/opencv-config 这篇文章有讲解opencv的安装与配置 一些常用库 opencv_core249d.lib opencv_imgproc249d.li ...