内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/20292988/enum-is-ienumerableint-returns-true-in-a-generic-method
enum Gender { Male, Female }
Gender g = Gender.Male;
bool b = g is int; // false, alright no issues
b = new[] { g } is IEnumerable<int>; // false, alright no issues
b = Is<Gender, int>(g); //false, alright no issues
b = Is<Gender[], IEnumerable<int>>(new[] { g }); // true, why on earth !!!
static bool Is<S, T>(S s)
{
return s is T;
}
为什么Gender []是IEnumerable<int>在通用情况下返回true?特别是当它们不兼容?
IEnumerable<int> c = new[] { Gender.Male }; //not compilable
在我链接的问题中,我已经绊倒了我!我认为这个问题是相关问题的关键.
对于有兴趣的人来说,这是数组的一个角落(不是真的枚举).关注 Eric Lippert’s blog 文章在答案中了解更多这种边缘案例.列表<T>不会发生这种情况例如:
b = Is<List<Gender>, IEnumerable<int>>(new List<Gender> { g }); // false, rightly
,解释了为什么uint []被CLI处理为int []而不是C#;我怀疑这里也是同样的解释).你甚至不需要泛型来证明:
Gender g = Gender.Male;
Console.WriteLine(new[] { g } is IEnumerable<int>); // False
Console.WriteLine((object)new[] { g } is IEnumerable<int>); // True
第一个是在编译时将表达式优化为false,因为C#编译器“知道”Gender []不是IEnumerable<int>.第二个是表达式生成在运行时评估的isinst指令.引用Eric Lippert:
It is unfortunate that C# and the CLI specifications disagree on this minor point but we are willing to live with the inconsistency.
代码日志版权声明:
翻译自:http://stackoverflow.com/questions/20292988/enum-is-ienumerableint-returns-true-in-a-generic-method
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Mybatis-plus 2.1.4 新增 mybatis 通用枚举自动注入
- mybatis-plus 升级 3.0.1 支持注解通用枚举解决方案
- mybatis-plus是如何只做增强不做改变之通用枚举篇
- mybatis-plus是如何只做增强不做改变之通用枚举篇(更新版)
- c# – 枚举时项目发生变化时是否会影响枚举?
- 测者的测试技术手册:Junit单元测试遇见的一个枚举类型的坑(枚举类型详解)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Django企业开发实战
胡阳 / 人民邮电出版社 / 2019-2 / 99.00元
本书以博客系统贯穿始末,介绍了Django的方方面面。书中共分四部分,第一部分介绍了正式进入编码之前的准备工作,内容包括需求分析、基础知识和Demo系统的开发;第二部分开始实现需求,内容涉及环境配置、编码规范以及项目结构规划,编写了Model层、admin页面、Form代码和View逻辑,引入了Bootstrap框架;第三部分重点介绍xadmin、django-autocomple-light和d......一起来看看 《Django企业开发实战》 这本书的介绍吧!