【发布时间】:2012-07-01 07:30:11
【问题描述】:
我正在尝试查找在 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 和/或逻辑双条件运算的代码。
【问题讨论】:
-
我的猜测是,虽然这两个字段的位值“足够真实”以至于 ToString() 会认为它们“真实”,但实际的 == 和 != 比较是按位进行的(因为它们是不应该以这种方式破坏的值类型),因此比较是不稳定的。你为什么做这个? :)
标签: c# boolean specifications language-specifications