不知道为什么我会收到InvalidCastException

时间:2012-06-24 19:01:24

标签: c# windows-phone-7 isolatedstorage .net trygetvalue

我收到了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);

1 个答案:

答案 0 :(得分:3)

您正在向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是否消失。