我得到一个InvalidCastException
,我不明白为什么。
这是引发异常的代码:
public static void AddToTriedList(string recipeID)
{
IList<string> triedIDList = new ObservableCollection<string>();
try
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (!settings.Contains("TriedIDList"))
{
settings.Add("TriedIDList", new ObservableCollection<Recipe>());
settings.Save();
}
else
{
settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);
}
triedIDList.Add(recipeID);
settings["TriedIDList"] = triedIDList;
settings.Save();
}
catch (Exception e)
{
Debug.WriteLine("Exception while using IsolatedStorageSettings in AddToTriedList:");
Debug.WriteLine(e.ToString());
}
}
AppSettings.cs:(提取)
// The isolated storage key names of our settings
const string TriedIDList_KeyName = "TriedIDList";
// The default value of our settings
IList<string> TriedIDList_Default = new ObservableCollection<string>();
...
/// <summary>
/// Property to get and set the TriedList Key.
/// </summary>
public IList<string> TriedIDList
{
get
{
return GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default);
}
set
{
if (AddOrUpdateValue(TriedIDList_KeyName, value))
{
Save();
}
}
}
GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default)
并且AddOrUpdateValue(TriedIDList_KeyName, value)
是微软推荐的常用方法;你可以在这里找到完整的代码。
编辑:我在这一行遇到了异常:
settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);