質問

I'm trying to find where in ECMA-334 (C# language specification) the following behavior is defined. The source program is as follows.

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;
}

The result of execution is the following.

Result of True==True is False.
Result of True!=True is True.
Result of True^True is True.

This violates both sections §14.9.4 and §14.10.3, so I'm assuming there's an exception stated elsewhere which covers these cases. Note that this does not affect code using AND, OR, NAND, or NOR operations, but it can affect code using XOR and/or logical biconditional operations.

役に立ちましたか?

解決

I doubt that this is specified at all. By the time you're explicitly laying out your structs, you're very likely to go into architecture-specific and implementation-specific behaviour.

I strongly suspect that the behaviour you're seeing can all be explained by imagining that all bool operations are effectively converted into integer operations, and then (where necessary) converting the result by checking whether it's non-zero. Normally that's fine, so long as all bool values use the same value in memory (1 or 0), but in your case you're giving it an unexpected value (2). So although a.boolValue and b.boolValue are both true, a.boolValue ^ b.boolValue has the effect of XORing the two bytes involved, giving 3, which is still converted to true where necessary.

It's best to avoid this sort of code, IMO. Did you actually have a need for it, or were you just curious?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top