0

Keynotfound 异常

public int getLastUniqueID()
{
    int lastID = 0;
    IsolatedStorageSettings uc = IsolatedStorageSettings.ApplicationSettings;

    List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];

    foreach (sMedication temp in medicationList) {
        lastID = temp.UniqueID;
    }

    return lastID;
}

它发生在以下行:

List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
4

2 回答 2

2

由于错误表明在访问值之前未在字典中找到键,请检查键是否存在

if(uc.Contains("medicationList"))
{
   // your code here
}
于 2012-06-24T04:35:53.180 回答
1

你会遇到这种方法的问题,因为如果检索到的应用程序设置中没有键“medicationList”,那么它会像你所见证的那样抛出异常。

尝试以下操作:

uc.TryGetValue<List<sMedication>>("medicationList", out medicationList)
if (medicationList != null)
{
   foreach(sMedication temp in medicationList)
   {
       lastID = temp.UniqueID;
       return lastID;
   }
}
else
{
   // handle the key not being there
}
于 2012-06-24T04:37:08.180 回答