5
// No overrides required .. let CLR take care of equal and hashcode.
Class Foo {public Name{get; set;} public Address{get; set;}} 

Dictionary<List<Foo>, int> map = new Dictionary<List<Foo>, int>();

質問:

このコードは大丈夫ですか?マップのキーになるには、Fooがequalsメソッドとhashcodeメソッドをオーバーライドする必要があることを理解しています。両方をオーバーライドするか、なしをオーバーライドします。

キーとしてのオブジェクトのリストについてはどうでしょうか。リストに関して、平等とはどういう意味ですか?上で定義されたマップは、「マップ内のオブジェクトが失われた」問題から安全ですか?

-カレフル

4

3 に答える 3

5

List<T>これは、元のインスタンスをキーとして使用する場合にのみ機能します。
同じアイテムで新しいものを作成した場合、とをオーバーライドしないためList<T>、同じキーとして扱われ ません。List<T>Equals()GetHashCode()

つまり、参照の等式を使用します。

それを変更したい場合は、を書くことができますIEqualityComparer<List<T>>

于 2012-06-11T21:08:51.607 に答える
3
List<int> a = new List<int>(1, 2, 3);
List<int> b = new List<int>(1, 2, 3); //different instance than a

Dictionary<List<int>, int>> map = new Dictionary<List<int>, int>>();
map.Add(a, a.Sum());
int aSum = map[b]; //KeyNotFoundException because this is a different instance.


HashSet<int> a = new HashSet<int>(1, 2, 3);
HashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a

Dictionary<HashSet<int>, int>> map1 = new Dictionary<HashSet<int>, int>>();
map1.Add(a, a.Sum());
int aSum = map1[b]; //KeyNotFoundException because this is a different instance.


HashSet<int> a = new HashSet<int>(1, 2, 3);
HashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a

Dictionary<HashSet<int>, int>> map2 = new Dictionary<HashSet<int>, int>>
  (HashSet<int>.CreateSetComparer()); //instance comparison not used - equal sets are equal
map2.Add(a, a.Sum());
int aSum = map2[b]; //6
于 2012-06-11T21:12:41.980 に答える
0

もちろん、できます、それは非常に限られています。簡単に言えFooば、リスト要素がすべて同じであっても、の組み合わせのリストFooは必ずしも同じではありませんList<Foo>。したがって、キーが同じであることを確認するため、または複雑なキー一致関数を作成するために、あいまいでない方法で参照を回避する必要があります。

より良いキータイプを使用する方がはるかに優れています。

于 2012-06-11T21:10:26.357 に答える