泛型类型不等于 [英] Generic types not equal
问题描述
在code段下方打印出类型是不一样的。为什么?我知道一个事实,即使用 interfaceOnMyType.GetGenericTypeDefinition()
就能解决问题,但为什么我应该这样做吗?
类节目
{
静态无效的主要(字串[] args)
{
VAR =的myType typeof运算(巴兹<>);
VAR interfaceOnMyType = myType.GetInterfaces()的SingleOrDefault()。
VAR exactType = typeof运算(IBAR<>);
如果(exactType == interfaceOnMyType)
{
Console.WriteLine(类型是相同的。);
}
其他
{
Console.WriteLine(类型是不一样的。);
}
到Console.ReadLine();
}
}
接口伊巴尔< T>
{
}
一流的巴兹< T> :伊巴尔< T>
{
}
原因是, interfaceOnMyType.IsGenericTypeDefinition
返回false,而 myType.IsGenericTypeDefinition
和 exactType.IsGenericTypeDefinition
都返回真。也就是说,仅仅因为你检索从泛型类型定义的非构造泛型类型并不意味着您检索类型本身是一个泛型类型定义。
The code segment below prints out "The types ARE NOT the same.". Why? I am aware of the fact that using interfaceOnMyType.GetGenericTypeDefinition()
will solve the problem, but why should I have to do that?
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>
{
}
The reason is that interfaceOnMyType.IsGenericTypeDefinition
returns false, whilst myType.IsGenericTypeDefinition
and exactType.IsGenericTypeDefinition
both return true. That is, just because you're retrieving a non-constructed generic type from a generic type definition does not mean that the type you retrieve is itself a generic type definition.
这篇关于泛型类型不等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!