【问题标题】:Getting type arguments of generic interfaces that a class implements获取类实现的泛型接口的类型参数
【发布时间】:2010-11-11 15:25:43
【问题描述】:

我有一个通用接口,比如 IGeneric。对于给定的类型,我想找到一个类通过 IGeneric 实现的泛型参数。

在这个例子中更清楚:

Class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { ... }

Type t = typeof(MyClass);
Type[] typeArgs = GetTypeArgsOfInterfacesOf(t);

// At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) }

GetTypeArgsOfInterfacesOf(Type t)的实现是什么?

注意:可以假设 GetTypeArgsOfInterfacesOf 方法是专门为 IGeneric 编写的。

编辑:请注意,我专门询问如何从 MyClass 实现的所有接口中过滤掉 IGeneric 接口。

相关:Finding out if a type implements a generic interface

【问题讨论】:

    标签: c# generics reflection


    【解决方案1】:

    要将其限制为特定风格的泛型接口,您需要获取泛型类型定义并与“开放”接口进行比较(IGeneric&lt;&gt; - 注意没有指定“T”):

    List<Type> genTypes = new List<Type>();
    foreach(Type intType in t.GetInterfaces()) {
        if(intType.IsGenericType && intType.GetGenericTypeDefinition()
            == typeof(IGeneric<>)) {
            genTypes.Add(intType.GetGenericArguments()[0]);
        }
    }
    // now look at genTypes
    

    或作为 LINQ 查询语法:

    Type[] typeArgs = (
        from iType in typeof(MyClass).GetInterfaces()
        where iType.IsGenericType
          && iType.GetGenericTypeDefinition() == typeof(IGeneric<>)
        select iType.GetGenericArguments()[0]).ToArray();
    

    【讨论】:

      【解决方案2】:
      typeof(MyClass)
          .GetInterfaces()
          .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
          .SelectMany(i => i.GetGenericArguments())
          .ToArray();
      

      【讨论】:

      • 好的,但这涉及 IDontWantThis 的 EvilType。我不想要 EvilType。
      • 已修复,只需要 Where() 上的一个简单条件。
      【解决方案3】:
        Type t = typeof(MyClass);
                  List<Type> Gtypes = new List<Type>();
                  foreach (Type it in t.GetInterfaces())
                  {
                      if ( it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IGeneric<>))
                          Gtypes.AddRange(it.GetGenericArguments());
                  }
      
      
       public class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { }
      
          public interface IGeneric<T>{}
      
          public interface IDontWantThis<T>{}
      
          public class Employee{ }
      
          public class Company{ }
      
          public class EvilType{ }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-31
        • 2018-05-26
        • 2011-05-29
        • 2019-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多