参见英文答案 >
C# byte type and literals 2个
我有什么理由不能使用以下代码吗?
我有什么理由不能使用以下代码吗?
ulong test(int a,int b) { return a == b ? 0 : 1; }
它告诉我:
Cannot implicitly convert type 'int' to 'ulong'. An explicit conversion exists (are you missing a cast?)
以下将有效:
ulong test(int a,int b) { return false ? 0 : 1; }
我知道如何解决这个问题.我只是想知道原因.
谢谢.
解决方法
我们来看看第二种方法得到的IL代码:
IL_0000: nop IL_0001: ldc.i4.1 IL_0002: conv.i8 IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret
在IL_0001,文字1被压入堆栈(因此表达式返回false?0:1;在编译时计算并作为常量嵌入到IL中),在IL_0002处,此文字将转换为Int64.
来自MSDN:
A constant-expression (Section 7.15) of type int can be converted to
type sbyte,byte,short,ushort,uint,or ulong,provided the value of
the constant-expression is within the range of the destination type.
由于1在ulong数据类型的范围内,因此这种转换将始终成功.编译器知道这一点,因此执行隐式转换.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。