简体   繁体   English

如何使用C#的三元运算符和两个字节值?

[英]How to use C#'s ternary operator with two byte values?

There doesn't seem to be a way to use C#'s ternary operator on two bytes like so: 似乎没有办法在两个字节上使用C#的三元运算符,如下所示:

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. 该代码当前无法使用“无法将源类型'int'转换为目标类型'byte'”进行编译,因为编译器将数字视为整数。 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. 显然没有指定后缀表示0和1是字节,因此唯一的解决方法是(a)将结果转换为字节或(b)使用if-else控件。

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. 演员阵容在这里不是问题,事实上,IL代码根本不应该有演员阵容。

Edit: The IL generated looks like this: 编辑:生成的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

You could always do: 你可以随时做:

var myByte = Convert.ToByte(myBool);

This will yield myByte == 0 for false and myByte == 1 for true. 这将产生myByte == 0表示false,myByte == 1表示true。

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

That compiles OK on VS2008. 在VS2008上编译好。

Correction : This compiles OK in VS2008: 更正 :这在VS2008中编译正常:

byte someByte = true ? 0 : 1;
byte someByte = false ? 0 : 1;

But this does not: 但这并不:

bool someBool = true;
byte someByte = someBool ? 0 : 1;

Odd! 奇!

Edit : Following Eric's advice (see his comment below), I tried this: 编辑 :按照Eric的建议(见下面的评论),我试过这个:

const bool someBool = true;
byte someByte = someBool ? 0 : 1;

And it compiles perfectly. 它编译得很完美。 Not that I distrust Eric; 不是我不相信埃里克; I just wanted to include this here for the sake of completeness. 为了完整起见,我只是想把它包含在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM