首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >.NET字典具有相同的键和值,但不是“相等”的

.NET字典具有相同的键和值,但不是“相等”的
EN

Stack Overflow用户
提问于 2010-02-08 08:52:24
回答 4查看 17.3K关注 0票数 19

此测试失败:

代码语言:javascript
复制
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等价物,而不是试图检查引用相等性。

EN

回答 4

Stack Overflow用户

发布于 2010-02-08 08:54:34

问题出在下面这行代码中:

代码语言:javascript
复制
Assert.AreEqual(dict, dictClone)

您正在比较对象引用,这两个引用并不相等。

票数 7
EN

Stack Overflow用户

发布于 2010-02-08 09:20:59

我使用了一个扩展方法来检查两个序列中是否有相等的项。

代码语言:javascript
复制
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;
}
票数 4
EN

Stack Overflow用户

发布于 2010-02-08 08:55:01

您完全不了解引用类型是如何工作的。

Dictionary不会覆盖object.Equals()。因此,它使用引用相等-基本上,如果两个引用指向同一个实例,则它们是相等的,否则它们就不相等。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2219047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档