Dizionario <>. Containskey dà runtimebinderexception
-
02-01-2020 - |
Domanda
in .cshtml Voglio controllare se una chiave esiste in un Directory<int, Object>
ma ottengo sempre un errore e non riesco a trovare perché.
Questo è il mio codice:
@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);
bool exist = ViewBag.Menus.ContainsKey(key);
}
.
L'errore che ottengo:
The best overloaded method match for System.Collections.Generic.Dictionary<int,Object>.this[int] has some invalid arguments
.
Quando utilizzo solo il .key o .Value funziona ancora.
Modifica - Soluzione
Qual è il problema, non lo so, ma ho risolto il problema con il seguente codice:
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);
}
. Soluzione 2
Qual è il problema, non lo so, ma ho risolto il problema con il seguente codice:
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);
}
. Altri suggerimenti
Puoi forse provare a usare TryGetValue invece di Containskey e vedere se funziona:
@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);
}
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow