在C#中,我们可以在不接触公共行为类的情况下将方法添加到公共行为类中吗?
在Unity csharp中,我想创建一个在C#中,我们可以在不接触公共行为类的情况下将方法添加到公共行为类中吗?,c#,behavior,C#,Behavior,在Unity csharp中,我想创建一个getOradComponent方法,它将简化相应的GetComponent和AddComponent(我想这是没有充分理由的) 通常的做法是: // this is just for illustrating a context using UnityEngine; class whatever : MonoBehavior { public Transform child; void whateverMethod () { BoxColli
getOradComponent
方法,它将简化相应的GetComponent
和AddComponent
(我想这是没有充分理由的)
通常的做法是:
// this is just for illustrating a context
using UnityEngine;
class whatever : MonoBehavior {
public Transform child;
void whateverMethod () {
BoxCollider boxCollider = child.GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = child.gameObject.AddComponent<BoxCollider>();
}
}}
。所以这是可行的:
// class whatever : MyMonoBehavior {
BoxCollider boxCollider = GetOrAddComponent(child, typeof(BoxCollider)) as BoxCollider;
但我希望我能这样写:
BoxCollider boxCollider = child.GetOrAddComponent<BoxCollider>();
BoxCollider-BoxCollider=child.GetOrAddComponent();
我唯一能想到的想法就是做起来太复杂了(用一个MyTransform
替换每个Transform
),因此不值得费心去尝试。至少不仅仅是为了更好的语法
但是是吗?或者有其他方法可以实现这一点吗?您可以使用c#3.0以来的扩展方法
公共静态扩展
{
公共静态void GetOrAdd(此实例)
{
//把逻辑放在这里
}
}
您是否尝试过使用?您可以这样声明它们:
public static class MyMonoExtensions {
public static T GetOrAddComponent<T>(this Transform child) where T: Component {
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
公共静态类MyMonoExtensions{
公共静态T GetOradComponent(此转换子级),其中T:Component{
T result=child.GetComponent();
如果(结果==null){
结果=child.gameObject.AddComponent();
}
返回结果;
}
}
您可以像调用实例方法一样调用它,然后:
child.GetOrAddComponent<BoxCollider>();
child.getOradComponent();
有关扩展方法的更多详细信息,请参见上面的链接 您可以使用扩展方法
public static class Extensions
{
public static T GetOrAddComponent<T>(this Transform child) where T : Component
{
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
公共静态类扩展
{
公共静态T GetOradComponent(此转换子级),其中T:Component
{
T result=child.GetComponent();
如果(结果==null){
结果=child.gameObject.AddComponent();
}
返回结果;
}
}
现在您可以使用
BoxCollider-BoxCollider=child.GetOrAddComponent()代码>只是说它们看起来只是扩展类型(IDE magic)的一部分-它们是完全独立的。@据我所知,扩展方法的编译方式就像“常规”方法一样,也就是说,第一个参数是实例本身。从IDE的角度来看,是的,这是一种魔力,但它反映了从运行时的角度将要做的事情。扩展方法编译成一种不同于它“扩展”的类型。这是一个静态方法,IDE使它看起来像是属于扩展类型。只是说,它们看起来只是扩展类型的一部分(IDE魔术)-它们是完全独立的。@Oded:但这可能正是OP想要的。如果没有扩展方法,像这样的静态方法将非常适合,尽管通过IDE发现的可能性要小得多。@Dilbert-True,我没说不是。我只是想指出,扩展方法是语法糖。我确实没有想过使用扩展方法,尽管我以前偶然发现过它!:p在这里,这是我的最终结果,感谢Botz3000:
child.GetOrAddComponent<BoxCollider>();
public static class Extensions
{
public static T GetOrAddComponent<T>(this Transform child) where T : Component
{
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}