我得到一个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)是Microsoft建议的常用方法;您可以找到完整的代码here

编辑:我在这一行有异常:

settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);

最佳答案

您要在ObservableCollection<Recipe>中添加settings

settings.Add("TriedIDList", new ObservableCollection<Recipe>());
                             // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^


但是,然后您读回了IList<string>,这显然是另一种类型:

settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);
                  // ^^^^^^^^^^^^^


您的triedIDList声明如下所示:

   IList<string> triedIDList = new ObservableCollection<string>();
// ^^^^^^^^^^^^^                // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^


首先,请确定一种类型,然后在所有这些位置使用完全相同的类型(即使您认为并非绝对必要),然后查看InvalidCastException是否消失。

关于c# - 不知道为什么我会收到InvalidCastException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11180354/

10-11 17:03