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 ...
随机推荐
- UI布局
1,初始化控件一般在onCreate()中完成,由于构造器中尚未完成控件加载,不能在其内初始化控件. 2,Activity子类必须含有无参构造.Intent.startActivity()方法调用的是 ...
- 爱莲(iLinkIT)的架构与原理
随着移动互联网时代的到来,手机正在逐步替代其他的设备,手机是电话.手机是即时通讯,手机是相机,手机是导航仪,手机是钱包,手机是音乐播放器……. 除此之外,手机还是一个大大的U盘,曾几何时,我们用一根长 ...
- 九款酷炫基于jquery实现的应用及源码
1.HTML5 Loading动画加载 五彩的圆环Loading 今天我们要分享一款基于HTML5的Loading加载动画特效,这款HTML5加载动画是一个五彩的圆环,圆环不停地转动从而体现加载正在进 ...
- 进程通信---FIFO
管道没有名字,所以只能在具有血缘关系的进程间使用,而在无名管道发展出来的有名管道FIFO,则有路径名与之相关联,以一种特殊设备文件形式存在于文件系统中,从而允许无亲缘关系的进程访问FIFO,下面看FI ...
- 控制反转 (inversion of control)
The inversion of control (IoC) pattern is abstract; it says that one should move dependency creation ...
- Lucene Field
org.apache.lucene.demo.IndexFiles类中,使用递归的方式去索引文件.在构造了一个IndexWriter索引器之后,就可以向索引器中添加Doucument了,执行真正地建立 ...
- Reveal 配置与使用
http://www.th7.cn/Program/IOS/201608/939231.shtml http://www.jianshu.com/p/abac941c2e8e 这个比较好.http:/ ...
- [大牛翻译系列]Hadoop(22)附录D.2 复制连接框架
附录D.2 复制连接框架 复制连接是map端连接,得名于它的具体实现:连接中最小的数据集将会被复制到所有的map主机节点.复制连接的实现非常直接明了.更具体的内容可以参考Chunk Lam的<H ...
- highchars
var drawChart = function(sourceUrl) { $.ajax({ "type" : "post", "url" ...
- pyQuery的安装
1. 直接通过pip安装 你会发现lxml怎么搞都报错,后来单独先安装libxml2和libxslt pip是找不到这个包的,只好百度.发现有很多的例子的解决方案.后来发现了个实用的. 2. 先安装l ...