如何使用C#的三元运算符有两个字节值? [英] How to use C#'s ternary operator with two byte values?

查看:389
本文介绍了如何使用C#的三元运算符有两个字节值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有要使用C#的三元运算符的两个字节像这样的方式:

 字节someByte = someBoolean? 0:1; 

这代码当前失败来编译无法将源类型'诠释'为目标类型字节 ,因为编译器会将数字为整数。显然没有指定后缀表明,0和1个字节,所以唯一的解决方法是:(一)把结果转换成一个字节或(b)为使用的if-else控制毕竟。



有什么想法?


解决方案

 字节someByte = someBoolean ? (字节)0:(字节)1; 



流延不是问题这​​里,实际上,IL代码不应有一个铸造在所有



编辑:
中的IL生成这个样子的:

  L_0010:// ldloc.0加载布尔变量堆栈
L_0011进行检查:brtrue.s L_0016 //分支如果为真,以抵消16
L_0013 :ldc.i4.1 //当假的:加载一个常数1
L_0014:br.s L_0017 //转到偏移17
L_0016:// ldc.i4.0真时:加载常数0
L_0017:// stloc.1结果存储在字节变量


There doesn't seem to be a way to use C#'s ternary operator on two bytes like so:

byte someByte = someBoolean ? 0 : 1;

That code currently fails to compile with "Cannot convert source type 'int' to target type 'byte'", because the compiler treats the numbers as integers. Apparently there is no designated suffix to indicate that 0 and 1 are bytes, so the only workarounds are to (a) cast the result into a byte or (b) to use an if-else control after all.

Any thoughts?

解决方案

byte someByte = someBoolean ? (byte)0 : (byte)1;

The cast is not a problem here, in fact, the IL code should not have a cast at all.

Edit: The IL generated looks like this:

L_0010: ldloc.0          // load the boolean variable to be checked on the stack
L_0011: brtrue.s L_0016  // branch if true to offset 16
L_0013: ldc.i4.1         // when false: load a constant 1
L_0014: br.s L_0017      // goto offset 17
L_0016: ldc.i4.0         // when true: load a constant 0
L_0017: stloc.1          // store the result in the byte variable

这篇关于如何使用C#的三元运算符有两个字节值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆