c# - 将类型传递给 C# 中的扩展?

标签 c# types extension-methods

在 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<Dog> d = t.MoreTricky<Dog>();)令人难以置信的是,我太蹩脚了,我不知道如何“正常”地传递类型。

最佳答案

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

关于c# - 将类型传递给 C# 中的扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900697/

相关文章:

c# - 使用 Blazor 加载外部 .NET Standard 2.0 程序集

c# - 是否可以提取具有主类属性的对象?

java - 在对象创建时定义类型,例如 HashMap<type here>

.Net 使用反射来定义 OfType

c# - 从 IViewComponentHelper 扩展方法中调用 Component.InvokeAsync()

c# - 我如何在 c# 中使用键对字典进行排序---是否可以使用 LINQ?

c# - 如何判断对象初始化程序何时完成

c# - 从类型名称获取可空类型

swift - 包含所有扩展方法的 Swift 模块

c# - IEnumerable 与 Ilist - IsNullOrEmpty 扩展方法