c# - C# Dictionary 中的 KeyNotFoundException 在根据什么更改属性值后,计算 GetHashCode。为什么?

标签 c# dictionary hash

请参阅下面的代码。

            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/

相关文章:

c# - 用户登录逻辑属于哪里?三层应用

c# - ASP.NET 如何在路径和查询完好无损的情况下对新域执行 HTTP 301

c# - 将复杂的 XML 反序列化为 C# 对象

python - 有效地反转和反转 python3.x OrderedDict

javascript - 带有#hash URL(或其他)的选项卡中的目标选项卡

mysql - 存储哈希值或生成哈希值的 bigint 变量哪个更好

java - Java Collection Framework 中 Set 的基于哈希的实现?

c# - 在 C# 中将字符串转换为 DateTime

dictionary - 如何在 f# 中创建 map 副本?

python - 将函数映射到 numpy 数组,改变参数