我打算在一个比较密集的代码中使用“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)
方法。显然这不是高效的,但它确实在一定程度上减少了正确实现的需要。 - Jeroen Vannevel==
表达式中比较的是.GetHashCode()
而不是KeyValuePair
。 - Jeroen Vannevel