我試圖在C#中使用int數組作爲鍵,並且我看到的行爲是意外的(對於我)。如何使用基本列表或列表作爲C#中的字典的關鍵字
var result = new Dictionary<int[], int>();
result[new [] {1, 1}] = 100;
result[new [] {1, 1}] = 200;
Assert.AreEqual(1, result.Count); // false is 2
它似乎也與列表一樣。
var result = new Dictionary<List<int>, int>();
result[new List<int> { 1, 1 }] = 100;
result[new List<int> { 1, 1 }] = 200;
Assert.AreEqual(1, result.Count); // false is 2
我期待Dictionary能夠使用Equals來決定Key是否存在於地圖中。這似乎並非如此。
有人可以解釋爲什麼以及如何讓這種行爲起作用嗎?
默認相等是數組/列表本身的實例相等,而不是數據結構的內容。你傳遞了兩個不同的實例,它們的內容相同,不會導致關鍵衝突。在構建字典時,您可以傳遞自己的'IEqualityComperer',該字典可以使用任何您想要比較鍵的邏輯來實現相等性。 –