簡體   English   中英

具有一個十進制字段的結構和defautl等於

[英]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)); 返回true,為什么呢? 如果進行按位比較,我認為十進制使用特殊位來表示符號

new Decim(5.00m).Equals (new Decim(5.000000m)); 報告為true,但是當我執行new Decim(5.00m).ToString()new Decim(5.000000m)).ToString()它將生成不同的值。 弦如何知道呢?

這是來自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的功能。

來源: 原始StackOverflow帖子

發現它: 有人可以用C#中的帶符號浮點解釋這種奇怪的行為嗎?

默認情況下等於:

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

因此,默認值等於將對十進制字段使用反射。 對於兩倍,它將執行fastEqualsCheck。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM