我可以使用对象列表作为字典键吗?

kar*_*hul 5 c#

// 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>();
Run Code Online (Sandbox Code Playgroud)

题:

这段代码看起来不错吗?我知道要成为Map中的一个键,Foo需要覆盖equals和hashcode方法 - 要么覆盖两者,要么不覆盖.

我想知道对象列表作为键是什么?当涉及到List时,平等意味着什么?上面定义的地图是否可以安全地避免"对象丢失在地图中"问题?

-Karephul

SLa*_*aks 5

这仅在您将原始List<T>实例用作键时才有效.
如果List<T>使用相同的项创建新项,则不会将其视为相同的键,因为 List<T>不会覆盖Equals()GetHashCode().

换句话说,它将使用引用相等.

如果你想改变它,你可以写一个IEqualityComparer<List<T>>.


Amy*_*y B 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
Run Code Online (Sandbox Code Playgroud)