Не уверен, почему я получаю InvalidCastException

Я получаю 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; Вы можете найти полный код здесь.

РЕДАКТИРОВАТЬ: я получил исключение в этой строке:

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

1 ответ

Решение

Вы добавляете 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 уходит.

Другие вопросы по тегам