C# Dictionary<> and mutable keys

后端 未结 5 1217
盖世英雄少女心
盖世英雄少女心 2020-12-06 18:09

I was told that one of the many reasons strings were made immutable in the C# spec was to avoid the issue of HashTables having keys changed when references to the string key

5条回答
  •  感情败类
    2020-12-06 18:42

    If you're using a mutable reference type as a key, the default implementation of GetHashCode() will guarantee hash equality regardless of object state (i.e. the hash is tied to the reference, not the state). You're correct, however, that a mutable type with value equality semantics (where GetHashCode presumably depends on state) is a bad choice for a dictionary key.

提交回复
热议问题