是否Dictionary.Equals()有一个实现? [英] Does Dictionary.Equals() have an implementation?

查看:102
本文介绍了是否Dictionary.Equals()有一个实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我比较到另一个词典(类型为IDictionary的变量)的字典。做d1.Equals(D2)产生false。下面写我自己的代码产生true。两者都是 System.Collections.Generic.Dictionary 。我缺少的东西还是词典不具有等于实现,比较键/值?



 私有静态布尔DictEquals< K,V>(IDictionary的< K,V> D1,IDictionary的< K,V> D2)
{
如果(d1.Count = d2.Count!)
返回FALSE;

的foreach(KeyValuePair< K,V>对在D1)
{
如果
返回假(d2.ContainsKey(pair.Key)!);

如果
返回false(等于(D2 [pair.Key],pair.Value)!);
}

返回真;
}


解决方案

Dictionary.Equals()使用默认从Object等,检查是否两个对象相同的参考一样,所有其他的默认集合。你可以自由地创建自己的子类使用值语义,虽然这通常包括条件都不变为好。


I have a Dictionary which I am comparing to another Dictionary (variables typed as IDictionary). Doing d1.Equals(d2) yields false. Writing my own code below yields true. Both are System.Collections.Generic.Dictionary. Am I missing something or does Dictionary not have an Equals implementation that compares keys/values?

private static bool DictEquals<K, V>(IDictionary<K, V> d1, IDictionary<K, V> d2)
{
    if (d1.Count != d2.Count)
        return false;

    foreach (KeyValuePair<K, V> pair in d1)
    {
        if (!d2.ContainsKey(pair.Key))
            return false;

        if (!Equals(d2[pair.Key], pair.Value))
            return false;
    }

    return true;
}

解决方案

Dictionary.Equals() uses the default Equals from Object, checking if the two objects are the same reference, as does all the other default collections. You're free to create your own subclass with value semantics, though that usually includes things being immutable as well.

这篇关于是否Dictionary.Equals()有一个实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆