扩展 MonoBehaviour 的扩展方法

Ger*_*ing 2 c# extension-methods unity-game-engine

我的目标是使用我的功能从 Unity3D 引擎扩展 MonoBehaviour 对象。这就是我所做的:

public static class Extensions {

    public static T GetComponentInChildren<T>(this UnityEngine.MonoBehaviour o, bool includeInactive) {
        T[] components = o.GetComponentsInChildren<T>(includeInactive);
        return components.Length > 0 ? components[0] : default(T);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我要使用它时,我只能this在调用前面使用时才能访问它:this.GetComponentInChildren(true)this应该是隐式的,对吧?

所以我认为我做错了什么......

这是我使用扩展的地方:

public class SomeController : MonoBehaviour {

    private SomeComponent component;

    void Awake() {
        component = this.GetComponentInChildren<SomeComponent>(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望我清楚了我的问题。有没有办法正确扩展 MonoBehaviour(不需要this显式使用关键字)或者为什么会这样?

g.p*_*dou 5

这是(语言)设计的。

如果您在类使用扩展方法,this则需要显式扩展方法。换句话说,显式的object expressionand.点运算符必须位于扩展方法调用之前。在内部使用的情况下,这是this

但是,对于您的情况,更好的解决方案是:

public class YourMonoBehaviourBase : MonoBehaviour {

    public T GetComponentInChildren<T>(bool includeInactive) {
        T[] components = GetComponentsInChildren<T>(includeInactive);
        return components.Length > 0 ? components[0] : default(T);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它:

public class SomeController : YourMonoBehaviourBase {

    private SomeComponent component;

    void Awake() {
        // No explicit this necessary:
        component = GetComponentInChildren<SomeComponent>(true);
    }
}
Run Code Online (Sandbox Code Playgroud)