Dictionary.ContainsKey return False, but a want True

前端 未结 12 947
野性不改
野性不改 2020-12-03 10:16
namespace Dic
{
public class Key
{
    string name;
    public Key(string n) { name = n; }
}

class Program
{
    static string Test()
    {
        Key a = new Key(         


        
12条回答
  •  情深已故
    2020-12-03 10:59

    you problem is that

    new Key("A").Equals(new Key("A"))==false.
    

    and

    new Key("A").GetHashCode()!=new Key("A").GetHashCode()
    

    fix that and it should work I think. To fix it override the Equals method and check if the name values are the same. You should also override GetHashCode if you are overriding Equals.

提交回复
热议问题