下面是带有注释的例子:

class Program
{
    // first version of structure
    public struct D1
    {
        public double d;
        public int f;
    }

    // during some changes in code then we got D2 from D1
    // Field f type became double while it was int before
    public struct D2 
    {
        public double d;
        public double f;
    }

    static void Main(string[] args)
    {
        // Scenario with the first version
        D1 a = new D1();
        D1 b = new D1();
        a.f = b.f = 1;
        a.d = 0.0;
        b.d = -0.0;
        bool r1 = a.Equals(b); // gives true, all is ok

        // The same scenario with the new one
        D2 c = new D2();
        D2 d = new D2();
        c.f = d.f = 1;
        c.d = 0.0;
        d.d = -0.0;
        bool r2 = c.Equals(d); // false! this is not the expected result        
    }
}

你觉得这个怎么样?


当前回答

简单的测试用例:

Console.WriteLine("Good: " + new Good().Equals(new Good { d = -.0 }));
Console.WriteLine("Bad: " + new Bad().Equals(new Bad { d = -.0 }));

public struct Good {
    public double d;
    public int f;
}

public struct Bad {
    public double d;
}

编辑:该错误也发生在float上,但仅在结构体中的字段加起来是8字节的倍数时才会发生。

其他回答

一半答案:

Reflector告诉我们ValueType.Equals()做的事情是这样的:

if (CanCompareBits(this))
    return FastEqualsCheck(this, obj);
else
    // Use reflection to step through each member and call .Equals() on each one.

不幸的是,CanCompareBits()和FastEquals()(都是静态方法)都是extern ([methodimmpl (MethodImplOptions.InternalCall)]),并且没有可用的源。

回到猜测为什么一种情况可以通过比特进行比较,而另一种情况不能(可能是对齐问题?)

错误出现在System的下面两行。ValueType:(我进入了引用源)

if (CanCompareBits(this)) 
    return FastEqualsCheck(thisObj, obj);

(这两个方法都是[methodimmpl (MethodImplOptions.InternalCall)])

当所有字段都是8字节宽时,CanCompareBits错误地返回true,导致两个不同但语义相同的值按位比较。

当至少有一个字段不是8字节宽时,CanCompareBits返回false,代码继续使用反射遍历字段并为每个值调用Equals,这将正确地将-0.0视为等于0.0。

以下是来自SSCLI的CanCompareBits源代码:

FCIMPL1(FC_BOOL_RET, ValueTypeHelper::CanCompareBits, Object* obj)
{
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    _ASSERTE(obj != NULL);
    MethodTable* mt = obj->GetMethodTable();
    FC_RETURN_BOOL(!mt->ContainsPointers() && !mt->IsNotTightlyPacked());
}
FCIMPLEND

只是一个10年前的bug的更新:它已经在。net Core中被修复了(免责声明:我是这篇PR的作者),这可能会在。net Core 2.1.0中发布。

这篇博客文章解释了这个错误,以及我是如何修复它的。

它必须与逐位比较相关,因为0.0与-0.0只差信号位。

如果D2像这样

public struct D2
{
    public double d;
    public double f;
    public string s;
}

这是真的。

如果你这样做

public struct D2
{
    public double d;
    public double f;
    public double u;
}

它仍然是假的。

如果结构体只保存双精度值,则它似乎为false。