代码之家  ›  专栏  ›  技术社区  ›  Serhat Ozgel

获取类实现的泛型接口的类型参数

  •  27
  • Serhat Ozgel  · 技术社区  · 15 年前

    我有一个通用接口,比如说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(类型T)的实现是什么?

    注意:可以假定gettypeargsofinterfacesof方法是专门为igeneric编写的。

    编辑: 请注意,我特别询问如何从MyClass实现的所有接口中筛选出IGeneric接口。

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

    3 回复  |  直到 15 年前
        1
  •  40
  •   Marc Gravell    15 年前

    要将其限制在一个特定风格的通用接口上,您需要获取通用类型定义并与“开放”接口进行比较。( IGeneric<> -注:未指定“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
  •  14
  •   Sam Harwell    15 年前
    typeof(MyClass)
        .GetInterfaces()
        .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
        .SelectMany(i => i.GetGenericArguments())
        .ToArray();
    
        3
  •  2
  •   chikak    15 年前
      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{ }