两个列表都是单独的实例,因此ReferenceEquals
返回false
,但默认情况下使用。您可以IEqualityComparer<IList<object>>
为字典构造函数实现自定义:
public class ListComparer : IEqualityComparer<IList<object>>
{
public bool Equals(IList<object> x, IList<object> y)
{
if (x == null || y == null) return false;
return x.SequenceEqual(y);
}
public int GetHashCode(IList<object> list)
{
if (list == null) return int.MinValue;
int hash = 19;
unchecked // Overflow is fine, just wrap
{
foreach (object obj in list)
if(obj != null)
hash = hash + obj.GetHashCode();
}
return hash;
}
}
现在它按预期工作:
var dict = new Dictionary<List<object>, double>(new ListComparer());
dict.Add(new List<object>() { "a", "b" }, 3);
double output = dict[new List<object>() { "a", "b" }]; // 3.0