When To Use IEquatable And Why

后端 未结 5 816
天命终不由人
天命终不由人 2020-12-07 17:31

What does IEquatable buy you, exactly? The only reason I can see it being useful is when creating a generic type and forcing users to implement and write a good equ

5条回答
  •  暖寄归人
    2020-12-07 18:25

    Further to the other answers here's a very good reason to be implementing IEquatable (and obviously overriding Equals(object) too) for value types. Just look at the default ValueType.Equals(object) code that gets called otherwise. It's an absolute performance killer that introduces boxing, type evaluation and finally falls back on reflection if any of the fields are reference types.

    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]).UnsafeGetValue(a);
            object obj4 = ((RtFieldInfo) fields[i]).UnsafeGetValue(obj);
            if (obj3 == null)
            {
                if (obj4 != null)
                {
                    return false;
                }
            }
            else if (!obj3.Equals(obj4))
            {
                return false;
            }
        }
        return true;
    }
    

    In certain scenarios (such as using the value type as a key in a dictionary) it can murder performance in one foul swoop.

提交回复
热议问题