[英]Dictionary<>.ContainsKey gives RuntimeBinderException
In .cshtml i want to check if a key exist in a Directory<int, Object>
but i get always an error and can't find why. 在.cshtml中,我想检查
Directory<int, Object>
是否存在键Directory<int, Object>
但是我总是收到错误,找不到原因。
This is my code: 这是我的代码:
@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);
bool exist = ViewBag.Menus.ContainsKey(key);
}
The error I get: 我得到的错误:
The best overloaded method match for System.Collections.Generic.Dictionary<int,Object>.this[int] has some invalid arguments
When I use only the .Key or .Value it still works. 当我仅使用.Key或.Value时,它仍然有效。
Edit - Solution 编辑-解决方案
What the problem is, I don't know, but I have solved the problem with the following code: 问题是什么,我不知道,但是我用以下代码解决了问题:
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);
}
Can you perhaps try using TryGetValue instead of ContainsKey and see if it works: 您是否可以尝试使用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);
}
What the problem is, I don't know, but I have solved the problem with the following code: 问题是什么,我不知道,但是我用以下代码解决了问题:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.