C#中扩展方法的使用

MSDN中这样定义扩展方法:扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 对于用 C#、F# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法没有明显区别。

扩展方法第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀,下面是一个简单的扩展方法实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class Extension {
    public static void CleanChild(this Transform tran) {
        foreach (Transform trans in tran)
        {
            UnityEngine.Object.Destroy(trans.gameObject);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestExtension : MonoBehaviour {
    void Start () {
        transform.CleanChild();
    }
}

虽然像是调用实例方法一样调用,但其实是静态方法。

原文地址:https://www.cnblogs.com/Mr147/p/9876717.html