为什么KeyValuePair不覆盖Equals()和GetHashCode()

本文关键字:GetHashCode Equals KeyValuePair 覆盖 为什么 | 更新日期: 2023-09-27 17:56:04

我打算在比较密集型代码中使用KeyValuePair,并且在检查它在.NET中的实现方式时感到困惑(如下)

为什么它不覆盖EqualsGetHashCode以提高效率(并且不实现==),而是使用基于反射的慢速默认实现?

我知道结构/值类型有一个基于其GetHashCode()Equals(object)方法反射的默认实现,但我认为如果你做很多比较,与覆盖相等相比

,它的效率非常低。

编辑 我做了一些测试,发现在我的场景(WPF 列表)中,默认KeyValuePair和我自己的结构实现覆盖GetHashCode()Equals(object)都比作为类的实现慢得多!


http://referencesource.microsoft.com/#mscorlib/system/collections/generic/keyvaluepair.cs,8585965bb176a426

// ==++==
// 
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
/*============================================================
**
** Interface:  KeyValuePair
** 
** <OWNER>[....]</OWNER>
**
**
** Purpose: Generic key-value pair for dictionary enumerators.
**
** 
===========================================================*/
namespace System.Collections.Generic {
    using System;
    using System.Text;
    // A KeyValuePair holds a key and a value from a dictionary.
    // It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>
    // and IReadOnlyDictionary<TKey, TValue>.
    [Serializable]
    public struct KeyValuePair<TKey, TValue> {
        private TKey key;
        private TValue value;
        public KeyValuePair(TKey key, TValue value) {
            this.key = key;
            this.value = value;
        }
        public TKey Key {
            get { return key; }
        }
        public TValue Value {
            get { return value; }
        }
        public override string ToString() {
            StringBuilder s = StringBuilderCache.Acquire();
            s.Append('[');
            if( Key != null) {
                s.Append(Key.ToString());
            }
            s.Append(", ");
            if( Value != null) {
               s.Append(Value.ToString());
            }
            s.Append(']');
            return StringBuilderCache.GetStringAndRelease(s);
        }
    }
}

为什么KeyValuePair不覆盖Equals()和GetHashCode()

正如其他答案指出的那样,您可以"免费"获得相等和哈希,因此您无需覆盖它们。但是,一分钱一分货;相等和散列的默认实现是 (1) 在某些情况下不是特别有效,并且 (2) 可以进行按位比较,因此可以执行诸如将负零和正零双精度在逻辑上相等时进行比较之类的操作。

如果您预计您的结构将经常在需要相等和哈希的上下文中使用,则应编写两者的自定义实现并遵循相应的规则和准则。

https://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

所以,回答你的问题:为什么没有人对特定类型这样做?可能是因为他们不相信这样做可以很好地利用他们的时间,而不是他们为改进基类库而必须做的所有其他事情。大多数人不会比较键值对的相等性,因此优化它可能不是一个高优先级。

这当然是推测;如果你真的想知道某件事在某一天没有完成的原因,你将不得不追踪所有没有做那个动作的人,并问他们在那天他们还在做什么更重要的事情。

它是一个

结构体,结构继承自ValueType,并且该类型已经覆盖了Equals和GetHashCode的实现。

它不支持==,执行以下操作甚至不会编译

var result = new KeyValuePair<string, string>("KVP", "Test1") ==
         new KeyValuePair<string, string>("KVP", "Test2");

您将收到错误"运算符'=='不能应用于类型KeyValuePair<string, string>KeyValuePair<string, string>的操作数"

KeyValuePair是一个

结构体(隐式继承自ValueType),并且相等工作得很好:

var a = new KeyValuePair<string, string>("a", "b");
var b = new KeyValuePair<string, string>("a", "b");
bool areEqual = a.Equals(b); // true

下面的参考资料显示了平等策略:

1- 相同的参考。

2-可以按位比较。

3-使用反射比较结构中的每个字段。

 public abstract class ValueType {
        [System.Security.SecuritySafeCritical]
        public override bool Equals (Object obj) {
            BCLDebug.Perf(false, "ValueType::Equals is not fast.  "+this.GetType().FullName+" should override Equals(Object)");
            if (null==obj) {
                return false;
            }
            RuntimeType thisType = (RuntimeType)this.GetType();
            RuntimeType thatType = (RuntimeType)obj.GetType();
            if (thatType!=thisType) {
                return false;
            }
            Object thisObj = (Object)this;
            Object thisResult, thatResult;
            // if there are no GC references in this object we can avoid reflection 
            // and do a fast memcmp
            if (CanCompareBits(this))
                return FastEqualsCheck(thisObj, obj);
            FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            for (int i=0; i<thisFields.Length; i++) {
                thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
                thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
                if (thisResult == null) {
                    if (thatResult != null)
                        return false;
                }
                else
                if (!thisResult.Equals(thatResult)) {
                    return false;
                }
            }
            return true;
        }