我试图找到在 ECMA-334(C# 语言规范)中定义以下行为的位置。源程序如下。
static void Main(string[] args)
{
TestStruct a = new TestStruct();
a.byteValue = 1;
TestStruct b = new TestStruct();
b.byteValue = 2;
Console.WriteLine(string.Format("Result of {0}=={1} is {2}.",
a.boolValue, b.boolValue, a.boolValue == b.boolValue));
Console.WriteLine(string.Format("Result of {0}!={1} is {2}.",
a.boolValue, b.boolValue, a.boolValue != b.boolValue));
Console.WriteLine(string.Format("Result of {0}^{1} is {2}.",
a.boolValue, b.boolValue, a.boolValue ^ b.boolValue));
}
[StructLayout(LayoutKind.Explicit, Pack = 1)]
struct TestStruct
{
[FieldOffset(0)]
public bool boolValue;
[FieldOffset(0)]
public byte byteValue;
}
执行结果如下。
Result of True==True is False.
Result of True!=True is True.
Result of True^True is True.
这违反了 §14.9.4 和 §14.10.3 两节,所以我假设其他地方有一个例外情况,涵盖了这些情况。请注意,这不会影响使用 AND、OR、NAND 或 NOR 运算的代码,但会影响使用 XOR 和/或逻辑双条件运算的代码。