下面的代码段打印出“类型不相同。”。为什么?我知道使用interfaceOnMyType.GetGenericTypeDefinition()
可以解决问题,但为什么我必须这样做呢?
class Program
{
static void Main(string[] args)
{
var myType = typeof(Baz<>);
var interfaceOnMyType = myType.GetInterfaces().SingleOrDefault();
var exactType = typeof(IBar<>);
if (exactType == interfaceOnMyType)
{
Console.WriteLine("The types ARE the same.");
}
else
{
Console.WriteLine("The types ARE NOT the same.");
}
Console.ReadLine();
}
}
interface IBar<T>
{
}
class Baz<T> : IBar<T>
{
}
interfaceOnMyType.GetGenericTypeDefinition()
返回接口的封闭构造类型,该类型与从返回的类型不同
typeof(IBar<>)
这是 MSDN 文章GetGenericTypeDefinition http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx,这里有一个很好的引用来解释它是如何工作的:
Given a Type
表示此构造类型的对象,GetGenericTypeDefinition
方法返回泛型类型定义。
Edit (the answer above is correct in some cases but wrong in this one):
我想我现在可能已经找到了。类型比较失败的原因是Type
从返回myType.GetInterfaces()
与接口本身的类型接近但不相同。
根据MSDN http://msdn.microsoft.com/en-us/library/system.type.fullname.aspx:
如果您使用BaseType
属性来获取基类型Derived
, the FullName
返回结果 Type 对象的属性null
(Visual Basic 中没有任何内容)。获取非空值FullName
,您可以使用GetGenericTypeDefinition
方法来获取泛型类型定义。
所以我认为这就是你所看到的问题。由于基本接口是通过检索的GetInterfaces
该调用检索到的任何类型都不会具有FullName
(source http://msdn.microsoft.com/en-us/library/system.type.basetype.aspx)。由于它没有FullName
类型将在比较中失败。
如果您比较的是您不是的构造类型,那么我最初写的内容将是正确的。不幸的是,我的第一个答案是完全错误的 - 我已经留下了它,以便留下的评论有意义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)