我的目标是用我的功能从MonoBehaviour引擎扩展Unity3D对象。我就是这样做的:
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);
}
}但是当我要使用它时,我只能在调用之前使用this才能访问它:this.GetComponentInChildren(true)但是this应该是隐式的,对吗?
所以我想我做错了什么..。
这里是我使用分机号的地方:
public class SomeController : MonoBehaviour {
private SomeComponent component;
void Awake() {
component = this.GetComponentInChildren<SomeComponent>(true);
}
}我希望我把问题弄清楚了。是否有一种正确扩展MonoBehaviour的方法(w/o需要显式使用this关键字),或者为什么要这样做?
发布于 2015-07-31 13:09:14
这是(语言)设计的。
如果在类中使用扩展方法,则需要显式this。换句话说,显式object expression和.点运算符必须在扩展方法调用之前。如果在内部使用,这是this
然而,就您的情况而言,更好的解决办法是:
public class YourMonoBehaviourBase : MonoBehaviour {
public T GetComponentInChildren<T>(bool includeInactive) {
T[] components = GetComponentsInChildren<T>(includeInactive);
return components.Length > 0 ? components[0] : default(T);
}
}然后你可以使用它:
public class SomeController : YourMonoBehaviourBase {
private SomeComponent component;
void Awake() {
// No explicit this necessary:
component = GetComponentInChildren<SomeComponent>(true);
}
}https://stackoverflow.com/questions/31746448
复制相似问题