加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:47:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 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?
参见英文答案 > 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数据类型的范围内,因此这种转换将始终成功.编译器知道这一点,因此执行隐式转换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读