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

40

我有一个通用接口,称为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接口。

相关链接:查找类型是否实现了泛型接口

3个回答

55

如果要将其限制为特定类型的通用接口,您需要获取通用类型定义并与“开放”接口(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();

18
typeof(MyClass)
    .GetInterfaces()
    .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
    .SelectMany(i => i.GetGenericArguments())
    .ToArray();

好的,但这涉及到IDontWantThis<EvilType>的邪恶类型。我不想要邪恶类型。 - Serhat Ozgel
修复了,只需要在Where()中加入一个简单的条件。 - Sam Harwell

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{ }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接