2

私は取得していますが、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);
4

1 に答える 1

3

にを追加しObservableCollection<Recipe>ていますsettings:

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

しかし、あなたは a を読み返していますがIList<string>、これは明らかに異なる型です:

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

の宣言はtriedIDList次のようになります。

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

まず、1 つのタイプを決定し、これらすべての場所でまったく同じタイプを使用して (厳密には必要ではないと思われる場合でも)、 がなくなるかどうかを確認しますInvalidCastException

于 2012-06-24T19:09:28.560 に答える