下面是带有注释的例子:

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

你觉得这个怎么样?


当前回答

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

其他回答

这对我来说是真的,Mono的gmcs 2.4.2.3。

简单的测试用例:

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字节的倍数时才会发生。

你觉得这个怎么样?

总是重写值类型上的Equals和GetHashCode。它将是快速和正确的。

它必须是零相关的,因为改变了直线

D.d = -0.0

to:

D.d = 0.0

结果比较是正确的…

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