简体   繁体   English

C#Dictionary.ContainsKey()始终返回false

[英]C# Dictionary.ContainsKey() always returns false

I have a Dictionary and every time I call the ContainsKey method it returns false. 我有一个Dictionary,每次调用ContainsKey方法时,它都会返回false。 Take the following example 请看下面的例子

 Boolean found = dict.ContainsKey(new Group("group1", "test"));

The found variable is false eventhough the visual studio debugger shows that a Group with the name "group1" and type "test" is present in dict. 尽管Visual Studio调试器显示dict中存在名称为“ group1”且类型为“ test”的Group,但找到的变量为false。 What is going on? 到底是怎么回事?

My Group class has two String fields (type and name) and I override the Equals method 我的Group类有两个String字段(类型和名称),我重写了Equals方法

public override bool Equals(object obj)
{
    Group otherGroup = (Group)obj;
    return this.name == otherGroup.name && this.type == otherGroup.type;
}

You should override GetHashCode method 您应该重写GetHashCode方法

An example of HashMethod for a class containing 2 string properties 包含2个字符串属性的类的HashMethod示例

public override int GetHashCode()
{
    unchecked
    {
        return ((name != null ? name.GetHashCode() : 0)*397) ^ (type != null ? type.GetHashCode() : 0);
    }
}

You need to override GetHashCode() : 您需要重写GetHashCode()

http://msdn.microsoft.com/en-us/library/ms182358(v=vs.80).aspx http://msdn.microsoft.com/zh-CN/library/ms182358(v=vs.80).aspx

GetHashCode returns a value based on the current instance that is suited for hashing algorithms and data structures such as a hash table. GetHashCode根据当前实例返回一个值,该值适用于哈希算法和数据结构(例如哈希表)。 Two objects that are the same type and are equal must return the same hash code to ensure that instances of System.Collections.HashTable and System.Collections.Generic.Dictionary work correctly. 相同类型且相等的两个对象必须返回相同的哈希码,以确保System.Collections.HashTable和System.Collections.Generic.Dictionary的实例正常工作。

I know this question already have an accepted answer but i'll share my dirty solution too. 我知道这个问题已经有一个可以接受的答案,但我也将分享我的肮脏解决方案。

Boolean found = 
   dict.Keys.Any(key => 
                 key.Equals("key", StringComparison.InvariantCultureIgnoreCase));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM