C#位或需要使用字节铸造* *有时 [英] C# Bitwise OR needs casting with byte *sometimes*
问题描述
我发现在C#编译器一个奇怪的局面。为什么下面的演员是必填的
使用系统;
类节目
{
私人常量字节BIT_ZERO_SET = 1;
私人常量字节BIT_ONE_SET = 2;
私人常量字节BIT_TWO_SET = 4;
静态无效的主要(字串[] args)
{
字节B = BIT_ZERO_SET | BIT_ONE_SET;
Console.WriteLine(二);
//不能编译,需要说投为int。
// B = | BIT_TWO_SET;
//Compiles...ugly
B =(字节)(B | BIT_TWO_SET);
Console.WriteLine(二);
Console.WriteLine(按回车键。);
到Console.ReadLine();
}
}
感谢。
< DIV CLASS =h2_lin>解决方案
的嫌疑,该行:
字节b = BIT_ZERO_SET | BIT_ONE_SET;
实际上是由C#编译器处理成恒定值的分配给b,而不是逐位。操作 - 它可以这样做,因为表达式的右边是在编译时完全确定。
行:
// b = | BIT_TWO_SET;
不编译因为逐位或运算促进其元素和评估为int,不一个字节。因为它涉及到运行值(B),它不能被编译成一个恒定的分配一样前行,需要铸造。
I found an odd situation in the C# compiler. Why the cast below is required?
using System;
class Program
{
private const byte BIT_ZERO_SET = 1;
private const byte BIT_ONE_SET = 2;
private const byte BIT_TWO_SET = 4;
static void Main(string[] args)
{
byte b = BIT_ZERO_SET | BIT_ONE_SET;
Console.WriteLine(b);
//Does not compile, says needs to cast to int.
//b = b | BIT_TWO_SET;
//Compiles...ugly
b = (byte)(b | BIT_TWO_SET);
Console.WriteLine(b);
Console.WriteLine("Press enter.");
Console.ReadLine();
}
}
Thanks.
Is suspect that the line:
byte b = BIT_ZERO_SET | BIT_ONE_SET;
is actually processed by the C# compiler into an assignment of a constant value to b, rather than a bitwise operation - it can do this because the right side of the expression is fully defined at compile time.
The line:
//b = b | BIT_TWO_SET;
doesn't compiled because the bit-wise OR operator promotes its elements and evaluates to an int, not a byte. Since it involves a runtime value (b) it cannot be compiled into a constant assignment like the line before, and requires casting.
这篇关于C#位或需要使用字节铸造* *有时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!