C# 扩展单行为的扩展方法
我的目标是使用我的功能扩展Unity3D引擎中的MonoBehavior对象。我就是这么做的:C# 扩展单行为的扩展方法,c#,unity3d,extension-methods,C#,Unity3d,Extension Methods,我的目标是使用我的功能扩展Unity3D引擎中的MonoBehavior对象。我就是这么做的: public static class Extensions { public static T GetComponentInChildren<T>(this UnityEngine.MonoBehaviour o, bool includeInactive) { T[] components = o.GetComponentsInChildren<T>
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);
}
}
我希望我把问题说清楚。是否有一种方法可以正确扩展MonoBehavior(不需要显式使用this
关键字),或者为什么它会这样 这是按(语言)设计的
如果在类内使用扩展方法,则需要显式此。换句话说,扩展方法调用之前必须有显式的对象表达式
和
点运算符。如果是内部使用,则为此
但是,在您的情况下,更好的解决方案是:
public class YourMonoBehaviourBase : MonoBehaviour {
public T GetComponentInChildren<T>(bool includeInactive) {
T[] components = GetComponentsInChildren<T>(includeInactive);
return components.Length > 0 ? components[0] : default(T);
}
}
公共类YourMonoBehavior基础:MonoBehavior{
public T GetComponentChildren(bool includeInactive){
T[]组件=GetComponentsInChildren(includeInactive);
返回组件。长度>0?组件[0]:默认值(T);
}
}
然后您可以使用它:
public class SomeController : YourMonoBehaviourBase {
private SomeComponent component;
void Awake() {
// No explicit this necessary:
component = GetComponentInChildren<SomeComponent>(true);
}
}
公共类SomeController:YourMonoBehavior库{
私有组件;
无效唤醒(){
//无需明确说明这一点:
component=getComponentChildren(true);
}
}
请看一下这个。
public class SomeController : YourMonoBehaviourBase {
private SomeComponent component;
void Awake() {
// No explicit this necessary:
component = GetComponentInChildren<SomeComponent>(true);
}
}