泛型类型不等于

编程入门 行业动态 更新时间:2024-10-21 06:28:37
本文介绍了泛型类型不等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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.

更多推荐

泛型类型不等于

本文发布于:2023-11-15 21:35:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598155.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不等于   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!