Keynotfound例外

时间:2012-06-24 04:29:02

标签: c# silverlight windows-phone-7

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"];

2 个答案:

答案 0 :(得分:2)

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

if(uc.Contains("medicationList"))
{
   // your code here
}

答案 1 :(得分:1)

你会遇到这种方法的问题,因为如果检索到的应用程序设置中没有关键的“药物列表”,那么它会抛出一个你见过的异常​​。

尝试以下方法:

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
}