用C# 拓展方法给现有的类增加 可用函数

来源:互联网 发布:手机网络总是2g 编辑:程序博客网 时间:2024/05/03 22:26

进天看到DotNet 公众号一篇文章,说是可以用C#的“拓展方法” 给现有的类增加函数,第一反应就是,这都可能?

然后手痒在Unity 里面尝试了一下,这样的写法:

using UnityEngine;
using System.Collections;

public class ExtendMethodTest : MonoBehaviour {

// Use this for initialization
void Start ()
{

string name = "";
    name=name.GetNotNullStr();
    Vector3 left = transform.Left()

}

}

public static class  ExtensionHelper
{

 public static string GetNotNullStr(this string strRes)
    {
        if (strRes == null)

 {
            strRes = "";
        }

    return strRes;
        }



     public static Vector3 Left(this Transform trans)
     {
        return -trans.right;
     }

}


没有语法报错。 kickass!


0 0
原创粉丝点击