【问题标题】:Why does KeyValuePair not override Equals() and GetHashCode()?为什么 KeyValuePair 不覆盖 Equals() 和 GetHashCode()?
【发布时间】:2016-07-10 03:54:29
【问题描述】:

我打算在一个比较密集的代码中使用KeyValuePair,并且困惑地检查它是如何在 .NET 中实现的(如下)

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

我知道结构/值类型的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);
        }
    }
}

【问题讨论】:

  • 结构有一个基于反射的默认实现,用于它们的GetHashCode() 和Equals(object) 方法。显然这不是高性能的,但它确实在一定程度上消除了正确实施它的需要
  • PS:您的代码编译的原因是因为您在== 表达式中比较的是.GetHashCode() 而不是KeyValuePair。
  • TKey 类型必须已经有一个很好的 GetHashCode 实现,否则字典会吃大亏。因此,CLR 为结构实现的默认 GetHashCode 已经足够好了。试图让 Equals 变得更好是没有意义的。

标签: c# .net value-type keyvaluepair


【解决方案1】:

正如其他答案所指出的,您可以“免费”获得平等和散列,因此您无需覆盖它们。然而,你得到你所支付的;相等和散列的默认实现是 (1) 在某些情况下不是特别有效,并且 (2) 可以进行按位比较,因此可以执行诸如比较负零和正零加倍在逻辑上相等时不同的事情。

如果您希望您的结构经常在需要相等和散列的上下文中使用,那么您应该编写两者的自定义实现并遵循适当的规则和指南。

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

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

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

【讨论】:

  • 每天我们都从 Eric 那里学到新东西。 new KeyValuePair&lt;int, int&gt;(-0, 1).Equals(new KeyValuePair&lt;int, int&gt;(0, 1));// true
  • @user3185569:这不是有趣的案例。有趣的情况是:struct S { public double d; public S(double d) { this.d = d; } } ... Console.WriteLine(new S(-0.0).Equals(new S(0.0))); 打印出False,尽管显然这两个双打是相等的。
  • 同样可怕:如果你的结构使用decimal,你最终会得到.Equals 返回true,但是对于GetHashCode 的调用会得到不同的结果,比如1.0M 和1.00M . volatileread.com/utilitylibrary/snippetcompiler?id=64818
  • @Brian:确实,这很糟糕。
  • 对于 .Net Core,github.com/dotnet/coreclr/pull/13164 和 github.com/dotnet/coreclr/issues/16545 可能会解决此问题。
【解决方案2】:

它是一个结构体,结构体继承自ValueType和那个类型already overrides the implementation of Equals and GetHashCode。

不支持==,做下面的连编译都编译不了

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

您将收到错误“运算符 '==' 不能应用于 KeyValuePair&lt;string, string&gt; 和 KeyValuePair&lt;string, string&gt; 类型的操作数”

【讨论】:

  • == 没有重载,所以它根本无法编译。
  • @Servy 谢谢,试用了一下,并为 == 部分添加了更详细的部分。
  • 我的问题是为什么他们不覆盖默认实现,因此,对不起,否决
  • @Mikhail 答案如下,ValueType 抽象类有一个通用的 Equals 功能比较结构内的每个字段。
  • @Mikhail 因为它不需要。 .NET 框架从不对 KeyValuePair 调用 .GetHashCode 或 .Equals。它在 TKey 上调用它。框架从不使用它,因此没有理由覆盖它。
【解决方案3】:

KeyValuePair 是一个结构(隐式继承自 ValueType),并且 Equality 工作得很好:

var a = new KeyValuePair<string, string>("a", "b");
var b = new KeyValuePair<string, string>("a", "b");

bool areEqual = a.Equals(b); // true

下面的参考展示了 Equals 策略:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    相关资源
    最近更新 更多