具有一个小数字段且默认等于的结构

Struct with one decimal field and defautl equals

默认 Equals() 如何在这样的结构上工作:

public struct Decim
{
    decimal x;

    public Decim (decimal x)
    {
        this.x = x;
    }
}

new Decim(-0m).Equals (new Decim(0m)); return 没错,为什么?如果它进行按位比较,我认为十进制使用特殊位来表示符号

new Decim(5.00m).Equals (new Decim(5.000000m)); 报告正确,但是当我执行 new Decim(5.00m).ToString()new Decim(5.000000m)).ToString() 时,它会产生不同的值。 to string 是怎么知道的?

这是来自 mscorlib 的 Equals 的反编译版本:

public override bool Equals(object obj)
{
    if (obj == null)
    {
        return false;
    }
    RuntimeType type = (RuntimeType) base.GetType();
    RuntimeType type2 = (RuntimeType) obj.GetType();
    if (type2 != type)
    {
        return false;
    }
    object a = this;
    if (CanCompareBits(this))
    {
        return FastEqualsCheck(a, obj);
    }
    FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
    for (int i = 0; i < fields.Length; i++)
    {
        object obj3 = ((RtFieldInfo) fields[i]).InternalGetValue(a, false);
        object obj4 = ((RtFieldInfo) fields[i]).InternalGetValue(obj, false);
        if (obj3 == null)
        {
            if (obj4 != null)
            {
                return false;
            }
        }
        else if (!obj3.Equals(obj4))
        {
            return false;
        }
    }
    return true;
}

你可以理解Equals 的作用。

来源:Original Whosebug post

找到了:Can anyone explain this strange behavior with signed floats in C#?

默认等于:

if (CanCompareBits(this)) // will return false for decimal
{
    return FastEqualsCheck(a, obj);
}

因此默认等于将对小数字段使用反射。对于 double 它将执行 fastEqualsCheck。