【问题标题】:Pass a type to an extension in c#?将类型传递给c#中的扩展?
【发布时间】:2016-10-20 10:06:03
【问题描述】:

在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;
  }

(所以,List&lt;Dog&gt; d = t.MoreTricky&lt;Dog&gt;();)令人难以置信的是,我太跛脚了,我不知道如何“正常”地做到这一点,传递类型。

【问题讨论】:

    标签: c# types extension-methods


    【解决方案1】:

    这很简单,您只需要使用GetComponent 的版本,它接受一个类型作为其参数之一并返回一个组件对象(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))
    

    【讨论】:

    • 啊……原来如此!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2012-04-16
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多