本文介绍了获取类实现的通用接口的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



在这个例子中更清楚:

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

类型t = typeof(MyClass);
类型[] typeArgs = GetTypeArgsOfInterfacesOf(t);

//此时,typeArgs必须等于{typeof(Employee),typeof(Company)}

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

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



编辑:请注意,我特别要求如何从MyClass实现的所有接口过滤出IGeneric接口。 b
$ b

相关:

解决方案

为了将其限制为通用接口的特定风格,您需要获取泛型类型定义,并与open接口( IGeneric<> c $ c> - 注释no指定的T)进行比较:

 列表<类型> genTypes = new List< Type>(); 
foreach(在t.GetInterfaces()中输入intType){
如果(intType.IsGenericType&&&& intType.GetGenericTypeDefinition()
== typeof(IGeneric<>)){
genTypes.Add(intType.GetGenericArguments()[0]);


//现在查看genTypes

或者作为LINQ查询语法:

  Type [] typeArgs =(
from typeof(MyClass).GetInterfaces( )
其中iType.IsGenericType
&& iType.GetGenericTypeDefinition()== typeof(IGeneric<>)
选择iType.GetGenericArguments()[0])。ToArray();


I have a generic interface, say IGeneric. For a given type, I want to find the generic arguments which a class imlements via IGeneric.

It is more clear in this example:

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

What is the implementation of GetTypeArgsOfInterfacesOf(Type t)?

Note: It may be assumed that GetTypeArgsOfInterfacesOf method is written specifically for IGeneric.

Edit: Please note that I am specifically asking how to filter out IGeneric interface from all the interfaces that MyClass implements.

Related: Finding out if a type implements a generic interface

解决方案

To limit it to just a specific flavor of generic interface you need to get the generic type definition and compare to the "open" interface (IGeneric<> - note no "T" specified):

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

Or as LINQ query-syntax:

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

这篇关于获取类实现的通用接口的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 23:49