有没有一种方法来确定一个泛型类型从一个特定的泛型类型定义建? [英] Is there a way to determine if a generic type is built from a specific generic type definition?
问题描述
我有一个泛型方法:
Func<IEnumerable<T>, bool> CreateFunction<T>()
其中, T
可以是任意数量的不同类型的。这种方法确实使用反射的东西一大堆,如果 T
是的IDictionary
,无论字典的<$ C的$ C> TKEY的和 TValue
我需要执行字典特定代码。
where T
can be any number of different types. This method does a bunch of stuff using reflection and if T
is an IDictionary
, regardless of the the dictionary's TKey
and TValue
I need to execute dictionary specific code.
所以,该方法可称为:
var f = CreateFunction<string>();
var f0 = CreateFunction<SomePocoType>();
var f1 = CreateFunction<IDictionary<string,object>>();
var f2 = CreateFunction<Dictionary<string,object>>();
var f3 = CreateFunction<SomeDerivedDictionaryType<string,object>>();
等。
etc.
澄清每@安迪的答案
最后,我想知道,如果 T
继承/工具的IDictionary
即使 T
本身词典
或派生自其他类型。该接口
Ultimately I want to know if T
inherits from/implements IDictionary
even if T
itself is Dictionary
or some other type that derives from that interface.
if(typeof(T) == typeof(IDictionary<,>)
不起作用,因为 T
是泛型类型不是泛型类型定义
doesn't work because T
is the generic type not the generic type definition.
和不知道 TKEY的
和 TValue
(其中在编译时不知道),我不能做一个比较的任何具体类型,我会知道,直到运行时。
And without knowing TKey
and TValue
(which are not known at compile time) I can't do a comparison to any concrete type that I would know about until runtime.
这是我想出的唯一的事与正在寻找该类型的名称或反射检查的方法,寻找方法,这将导致我相信它是一本字典(即寻找的containsKey
和 get_Item
)。
The only thing that I've come up with are looking at the type's name or inspecting its method with reflection, looking for methods that would lead me to believe it is a dictionary (i.e. look for ContainsKey
and get_Item
).
有没有作出这种决定的任何直接的方式?
Is there any straightforward way to make this sort of determination?
推荐答案
您可以做类似
class Program
{
static void Main(string[] args)
{
Example<IDictionary<int, string>>.IsDictionary();
Example<SortedDictionary<int, string>>.IsDictionary();
Example<Dictionary<int, string>>.IsDictionary();
Console.ReadKey();
}
}
public class Example<T>
{
public static void IsDictionary()
{
if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))
{
Console.WriteLine("Is IDictionary");
}
else
{
Console.WriteLine("Not IDictionary");
}
}
}
这篇关于有没有一种方法来确定一个泛型类型从一个特定的泛型类型定义建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!