2012-10-19 75 views
2

假设我有一个泛型类型的运行时对象和相同类的原始泛型类型,例如,如何从类型参数的泛型类型中提取原始泛型类型

var type = (new List<Int32>()).GetType(); 
var genericListType = typeof(List<>); 

我需要一种方法GetRawGenericType,使表达

GetRawGenericType(type) == genericListType 

返回true。有没有办法来实现这个?

备注:

我不知道的对象的类型,它可能是任何泛型类型。 在我写我必须知道确切的泛型类型,因为它会被用来作为一个字典的关键,例如代码:

private readonly Dictionary<Type, TValue> Mapping = 
    new Dictionary<Type, TValue> { 
      {typeof(IEnumerable<>), *SomeValue*}, 
      ... 
     } 

预先感谢您花费的时间。

+0

BTW您的第一线可能是简单的'变种类型= typeof运算(名单);' – AakashM

+0

@AakashM:如果在第一类型线实际上是已知的,那么整个问题是毫无意义的。这可能类似于'var type = someObjectSentToAMethod.GetType();'。 – Guffa

+0

@Guffa谢谢) – danyloid

回答

3

使用GetGenericTypeDefinition method

var type = (new List<Int32>()).GetType(); 
var genericListType = typeof(List<>); 

Console.WriteLine(type.GetGenericTypeDefinition() == genericListType); 

显示

true