C# 获取类实现的泛型接口的类型参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1142105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting type arguments of generic interfaces that a class implements
提问by Serhat Ozgel
I have a generic interface, say IGeneric. For a given type, I want to find the generic arguments which a class imlements via IGeneric.
我有一个通用接口,比如 IGeneric。对于给定的类型,我想找到类通过 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)?
GetTypeArgsOfInterfacesOf(Type t) 的实现是什么?
Note: It may be assumed that GetTypeArgsOfInterfacesOf method is written specifically for IGeneric.
注意:可以假设 GetTypeArgsOfInterfacesOf 方法是专门为 IGeneric 编写的。
Edit:Please note that I am specifically asking how to filter out IGeneric interface from all the interfaces that MyClass implements.
编辑:请注意,我特别询问如何从 MyClass 实现的所有接口中过滤掉 IGeneric 接口。
Related: Finding out if a type implements a generic interface
采纳答案by Marc Gravell
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):
要将其限制为特定类型的通用接口,您需要获取通用类型定义并与“开放”接口进行比较(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
Or as LINQ query-syntax:
或者作为 LINQ 查询语法:
Type[] typeArgs = (
from iType in typeof(MyClass).GetInterfaces()
where iType.IsGenericType
&& iType.GetGenericTypeDefinition() == typeof(IGeneric<>)
select iType.GetGenericArguments()[0]).ToArray();
回答by Sam Harwell
typeof(MyClass)
.GetInterfaces()
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
.SelectMany(i => i.GetGenericArguments())
.ToArray();
回答by chikak
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{ }