【发布时间】:2019-01-22 15:39:08
【问题描述】:
我最近不得不在 .NET 中进行一些反思,并在比较泛型类型定义时偶然发现了一个奇怪的行为。
我必须通过从 LINQ Expression 中提取 Type 对象来确定类型是否为 IDictionary<,>,因此我无法使用 is 运算符来确定它。此外,我不得不忽略类型参数,换句话说,唯一重要的是我是否正在处理任何键/值类型的IDictionary<,>。
我从以下开始:
// Just a placeholder, in my code I have no way of knowing that it
// is a Dictionary of string keys and string values or even that it
// is a dictionary at all.
typeof(Dictionary<string, string>)
.GetGenericTypeDefinition()
.GetInterfaces()
.Any(i => i == typeof(IDictionary<,>))
我假设因为我正在阅读泛型类型定义的接口,所以我会得到泛型接口定义。更奇怪的是,当我将上面的代码粘贴到 LINQPad 时,它返回了以下内容:
typeof(IDictionary<TKey,TValue>) // it appears here
typeof(ICollection<KeyValuePair<TKey,TValue>>)
typeof(IEnumerable<KeyValuePair<TKey,TValue>>)
typeof(IEnumerable)
typeof(IDictionary)
typeof(ICollection)
typeof(IReadOnlyDictionary<TKey,TValue>)
typeof(IReadOnlyCollection<KeyValuePair<TKey,TValue>>)
typeof(ISerializable)
typeof(IDeserializationCallback)
但由于某种原因,Any 方法中的比较对于这些元素中的任何一个都没有成功。但是,如果我像这样获得接口本身的泛型类型定义:
typeof(Dictionary<string, string>)
.GetGenericTypeDefinition()
.GetInterfaces()
.Select(i => i.IsGenericType ? i.GetGenericTypeDefinition() : i)
.Any(i => i == typeof(IDictionary<,>))
然后它会返回 true 就像它应该的那样。
这是为什么呢?当在泛型类型定义上调用泛型接口定义本身时,.GetInterfaces() 方法返回的接口不是已经定义了吗?如果是这样,当我在 LINQPad 中检查返回的接口时,它们似乎是泛型类型定义的解释是什么?
我想这与接口的类型参数可以完全独立于实现者的泛型参数这一事实有关,例如:
public class MyGenericType<TKey, TValue> : ISomeInterface<object> ...
但是看起来很奇怪,返回的Type 对象似乎没有反映这种情况(正如我在这个特定示例中所期望的那样),并且从“外观”来看,它们似乎是泛型类型定义,但它们没有被识别为那个。
【问题讨论】:
-
typeof(IDictionary<,>).IsAssignableFrom(i.GetType())可以代替i == typeof(IDictionary<,>)工作吗? -
@J.vanLangen 不,因为您不能指望该方法能够确定是否可以将某些内容分配给“不确定类型”。但即使是这样,也无法解释我的问题。
-
可能与 stackoverflow.com/questions/1735035/… 有关,但我现在无法深入研究。
标签: c# .net generics reflection