Dictionary<> .ContainsKey给出了RuntimeBinderException

时间:2014-08-01 08:46:25

标签: c# dictionary containskey

在.cshtml中,我想检查一个密钥是否存在于Directory<int, Object>中,但我总是出错,无法找到原因。

这是我的代码:

@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
    int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);

    bool exist = ViewBag.Menus.ContainsKey(key);
}

我得到的错误:

The best overloaded method match for System.Collections.Generic.Dictionary<int,Object>.this[int] has some invalid arguments

当我只使用.Key或.Value时,它仍然有效。

修改 - 解决方案

问题是什么,我不知道,但我用以下代码解决了这个问题:

foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
    {
        int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);

        bool exist = ((Dictionary<int, Object>)ViewBag.Menus).ContainsKey(key);
}

2 个答案:

答案 0 :(得分:0)

您是否可以尝试使用TryGetValue而不是ContainsKey,看看它是否有效:

@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
    int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key); 
    Object outValue;
    bool exist = Menus.TryGetValue(key, out outValue);
}

答案 1 :(得分:0)

问题是什么,我不知道,但我已用以下代码解决了问题:

foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
    {
        int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);

        bool exist = ((Dictionary<int, Object>)ViewBag.Menus).ContainsKey(key);
}