c# – 在内联中返回ulong-if

c# – 在内联中返回ulong-if,第1张

概述参见英文答案 > C# byte type and literals                                     2个 我有什么理由不能使用以下代码吗? ulong test(int a, int b){ return a == b ? 0 : 1;} 它告诉我: Cannot implicitly convert type 'int' to 'ulong' 参见英文答案 > 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:  nopIL_0001:  ldc.i4.1IL_0002:  conv.i8IL_0003:  stloc.0IL_0004:  br.s       IL_0006IL_0006:  ldloc.0IL_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数据类型的范围内,因此这种转换将始终成功.编译器知道这一点,因此执行隐式转换.

总结

以上是内存溢出为你收集整理的c# – 在内联中返回ulong-if全部内容,希望文章能够帮你解决c# – 在内联中返回ulong-if所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1252310.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存