ContainsKey()在字典中找不到对象 [英] ContainsKey() dont find an object in Dictionary

查看:318
本文介绍了ContainsKey()在字典中找不到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个家庭作业,我必须实现一些方法.我可以执行上载方法,在该方法中,我必须上载元素中的字典.如果密钥已经在字典中,那么我必须更新值.如果键不在词典中,则必须添加该元素.在Foreach中,我可以做到这一点.

I was a homework, I had to implement some method. I can do the upload method, where I had to upload an dictionary in elements. If the Key had already in the Dictionary I had to update the Value. If the key wasn't in the Dictionary, I had to add that element. In Foreach I could do that.

在if情况下,方法永远不会为true,只有else情况下才执行. (以其他方式,我尝试了if(alcDictionary.Keys==alc)-但不起作用).我不知道为什么有人可以向我解释我的问题在哪里?为什么不执行If案例. (总是写出找不到",而不是找到")

In the method never true in the if case, only the else case execute. ( In other way I tried to if(alcDictionary.Keys==alc) -but isn't work). I don't know why. Somebody can explain me where is my problem? Why never execute the If case. (Always write out "dont find", and not the "find")

我已经使用containsKey()编写了此方法:

I've written this method with containsKey():

     public void Upload(Alcohol alc, int dl)
    {
        int d = 0;
        Alcohol s = null;
        if (alcDictionary.ContainsKey(alc))
        {

            Console.WriteLine("I find");
            d = alcDictionary[alc];
            alcDictionary[alc] = d + dl;
        }
        else
        {
            Console.WriteLine("dont find");
            alcDictionary.Add(alc, dl);
        }

使用Foreach(效果很好!)

With Foreach ( It works good!)

            int d = 0;
        Alcohol s = null;
        foreach (var item in alcDictionary)
        {
            if (item.Key.Equals(alc))
            {
                d = item.Value;
                s = item.Key;
            }
        }
        if (s != null)
        {
            alcDictionary[s] = d + dl;
        }
        else
        {
            alcDictionary.Add(alc, dl);
        }

其他一些代码:

    public Kocsma()
    {
        Upload(new Alcohol("Borsodi alc", 160, 4.6), 1000);
        Upload(new Alcohol("Pilsner Urquell", 250, 4.4), 800);
        Upload(new Alcohol("Soproni Ászok", 150, 4.5), 900);
        Upload(new Alcohol("Dreher Classic", 200, 5.2), 600);
    }


    static void Main(String[] args)
    {
        Alcohol b = new Alcohol("Borsodi alc", 160, 4.6); //34
        Alcohol c = new Alcohol("Bratista alc", 230, 4.5); // 51
        Alcohol d = new Alcohol("Soproni Ászok", 150, 4.5); // 33,3

        Kocsma pub = new Kocsma();

        pub.Upload(c, 300);
        pub.Upload(d, 450);
        pub.Upload(b, 100);


    }

推荐答案

您需要在键类中正确覆盖GetHashCode().

You need to correctly override GetHashCode() in your key class.

GetHashCode()必须为相等的对象返回相等的值.

GetHashCode() must return equal values for equal objects.

这篇关于ContainsKey()在字典中找不到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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