Dictionary<祝辞.ContainsKey给出RuntimeBinderException
本文关键字:给出 RuntimeBinderException ContainsKey 祝辞 Dictionary | 更新日期: 2023-09-27 18:15:53
在.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);
}
你可以尝试使用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);
}
问题是什么,我不知道,但我已经用以下代码解决了问题:
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);
}