似乎没有办法在两个字节上使用C#的三元运算符,如下所示:
byte someByte = someBoolean ? 0 : 1;
该代码当前无法使用“无法将源类型'int'转换为目标类型'byte'”进行编译,因为编译器将这些数字视为整数。显然没有指定的后缀表示0和1是字节,因此唯一的解决方法是(a)将结果转换为字节或(b)使用if-else控件。
有什么想法吗?
答案 0 :(得分:19)
byte someByte = someBoolean ? (byte)0 : (byte)1;
演员阵容在这里不是问题,事实上,IL代码根本不应该有演员阵容。
修改强> 生成的IL看起来像这样:
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
答案 1 :(得分:6)
你总是可以这样做:
var myByte = Convert.ToByte(myBool);
这将产生myByte == 0表示false,myByte == 1表示true。
答案 2 :(得分:4)
byte someByte = (byte)(someBoolean ? 0 : 1);
答案 3 :(得分:3)
在VS2008上编译好。
更正:这在VS2008中编译正常:
byte someByte = true ? 0 : 1;
byte someByte = false ? 0 : 1;
但此不会:
bool someBool = true;
byte someByte = someBool ? 0 : 1;
奇!
编辑:根据Eric的建议(请参阅下面的评论),我试过了:
const bool someBool = true;
byte someByte = someBool ? 0 : 1;
它编译得很完美。不是我不相信埃里克;为了完整起见,我只是想把它包含在这里。