此测试失败:
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestMethod()]
public void dictEqualTest() {
IDictionary<string, int> dict = new Dictionary<string, int>();
IDictionary<string, int> dictClone = new Dictionary<string, int>();
for (int x = 0; x < 3; x++) {
dict[x.ToString()] = x;
dictClone[x.ToString()] = x;
}
Assert.AreEqual(dict, dictClone); // fails here
Assert.IsTrue(dict.Equals(dictClone)); // and here, if the first is commented out
Assert.AreSame(dict, dictClone); // also fails
}
我是不是误解了Dictionary
的工作原理?
我正在寻找.equals()
的Java等价物,而不是试图检查引用相等性。
发布于 2010-02-08 08:54:34
问题出在下面这行代码中:
Assert.AreEqual(dict, dictClone)
您正在比较对象引用,这两个引用并不相等。
发布于 2010-02-08 09:20:59
我使用了一个扩展方法来检查两个序列中是否有相等的项。
public static bool CheckForEquality<T>(this IEnumerable<T> source, IEnumerable<T> destination)
{
if (source.Count() != destination.Count())
{
return false;
}
var dictionary = new Dictionary<T, int>();
foreach (var value in source)
{
if (!dictionary.ContainsKey(value))
{
dictionary[value] = 1;
}
else
{
dictionary[value]++;
}
}
foreach (var member in destination)
{
if (!dictionary.ContainsKey(member))
{
return false;
}
dictionary[member]--;
}
foreach (var kvp in dictionary)
{
if (kvp.Value != 0)
{
return false;
}
}
return true;
}
发布于 2010-02-08 08:55:01
您完全不了解引用类型是如何工作的。
Dictionary
不会覆盖object.Equals()
。因此,它使用引用相等-基本上,如果两个引用指向同一个实例,则它们是相等的,否则它们就不相等。
https://stackoverflow.com/questions/2219047
复制相似问题