请参阅下面的代码。
static void Main(string[] args)
{
// Create Dictionary
var dict = new Dictionary<TestClass, ValueClass>();
// Add data to dictionary
CreateSomeData(dict);
// Create a List
var list = new List<TestClass>();
foreach(var kv in dict) {
// Swap property values for each Key
// For example Key with property value 1 will become 6
// and 6 will become 1
kv.Key.MyProperty = 6 - kv.Key.MyProperty + 1;
// Add the Key to the List
list.Add(kv.Key);
}
// Try to print dictionary and received KeyNotFoundException.
foreach (var k in list)
{
Console.WriteLine($"{dict[k].MyProperty} - {k.MyProperty}");
}
}
static void CreateSomeData(Dictionary<TestClass, ValueClass> dictionary) {
dictionary.Add(new TestClass {MyProperty = 1}, new ValueClass {MyProperty = 1});
dictionary.Add(new TestClass {MyProperty = 2}, new ValueClass {MyProperty = 2});
dictionary.Add(new TestClass {MyProperty = 3}, new ValueClass {MyProperty = 3});
dictionary.Add(new TestClass {MyProperty = 4}, new ValueClass {MyProperty = 4});
dictionary.Add(new TestClass {MyProperty = 5}, new ValueClass {MyProperty = 5});
dictionary.Add(new TestClass {MyProperty = 6}, new ValueClass {MyProperty = 6});
}
键值类:
namespace HashDictionaryTest
{
public class TestClass
{
public int MyProperty { get; set; }
public override int GetHashCode() {
return MyProperty;
}
}
}
namespace HashDictionaryTest
{
public class ValueClass
{
public int MyProperty { get; set; }
public override int GetHashCode() {
return MyProperty;
}
}
}
我在 Ubuntu 上使用 dotnet core 2.2。我只是出于好奇而做了这个测试。然而,令我惊讶的是,我遇到了 KeyNotFoundException。
我预计会收到错误的值。但是,我收到了上述异常。
我想知道的是,为什么会出现这个错误?生成 HashCode 的最佳做法是什么,以便我们可以避免此类问题?
最佳答案
What I want to know is, why we got this error?
GetHashCode 有指南,也有规则。如果您违反准则,您将获得糟糕的表现。如果您违反了规则,事情就会破裂。
你违反了规则。 GetHashCode 的规则之一是当一个对象在字典中时,它的散列码不能改变。另一个规则是相同的对象必须有相同的散列码。
你违反了规则,所以事情就坏了。那是你的错;不要违反规则。
What is the best practice in generating the HashCode so that we can avoid such issues?
有关规则和准则的列表,请参阅:
https://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/
关于c# - C# Dictionary 中的 KeyNotFoundException 在根据什么更改属性值后,计算 GetHashCode。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509316/