将类型传递给 C# 中的扩展?
Pass a type to an extension in c#?
在 Unity 中,假设你有 class Explosion:MonoBehavior
,使用 GetComponent
你可以简单地
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
if ( t.GetComponent<Explosion>() )
result.Add( t );
}
该列表现在包含所有具有“爆炸”组件的直接活动或非活动子项。
我想做一个扩展,按照
List<Explosion> = transform.Tricky(typeof(Explosion));
所以,扩展看起来像...
public static List<Transform> Tricky(this Transform here, Type ttt)
{
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
if ( t.GetComponent<ttt>() )
result.Add( t );
}
return result;
}
然而我完全没有弄明白这一点。怎么做?
注意!
我知道如何使用泛型来做到这一点:
public static List<T> MoreTricky<T>(this Transform here)
{
List<T> result = new List<T>();
foreach (Transform t in here)
{
T item = t.GetComponent<T>(); if (item != null) result.Add(item);
}
return result;
}
(so, List<Dog> d = t.MoreTricky<Dog>();
) 难以置信,我很蹩脚,我不知道如何“正常”地传递类型。
这很简单,您只需要使用将类型作为其参数之一的 GetComponent
版本和 returns 组件对象 (public Component GetComponent(Type type);
),它是列出的第一个 in the documentation。请注意,在文档中,他们在非通用重载部分中显示的示例是针对通用重载的,他们在页面上没有非通用示例。
public static List<Transform> Tricky(this Transform here, Type ttt)
{
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
Component item = t.GetComponent(ttt);
if (item)
result.Add(t);
}
return result;
}
你可以这样称呼它
List<Transform> explosionTransfoms = transform.Tricky(typeof(Explosion))
在 Unity 中,假设你有 class Explosion:MonoBehavior
,使用 GetComponent
你可以简单地
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
if ( t.GetComponent<Explosion>() )
result.Add( t );
}
该列表现在包含所有具有“爆炸”组件的直接活动或非活动子项。
我想做一个扩展,按照
List<Explosion> = transform.Tricky(typeof(Explosion));
所以,扩展看起来像...
public static List<Transform> Tricky(this Transform here, Type ttt)
{
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
if ( t.GetComponent<ttt>() )
result.Add( t );
}
return result;
}
然而我完全没有弄明白这一点。怎么做?
注意!
我知道如何使用泛型来做到这一点:
public static List<T> MoreTricky<T>(this Transform here)
{
List<T> result = new List<T>();
foreach (Transform t in here)
{
T item = t.GetComponent<T>(); if (item != null) result.Add(item);
}
return result;
}
(so, List<Dog> d = t.MoreTricky<Dog>();
) 难以置信,我很蹩脚,我不知道如何“正常”地传递类型。
这很简单,您只需要使用将类型作为其参数之一的 GetComponent
版本和 returns 组件对象 (public Component GetComponent(Type type);
),它是列出的第一个 in the documentation。请注意,在文档中,他们在非通用重载部分中显示的示例是针对通用重载的,他们在页面上没有非通用示例。
public static List<Transform> Tricky(this Transform here, Type ttt)
{
List<Transform> result = new List<Transform>();
foreach (Transform t in here)
{
Component item = t.GetComponent(ttt);
if (item)
result.Add(t);
}
return result;
}
你可以这样称呼它
List<Transform> explosionTransfoms = transform.Tricky(typeof(Explosion))