【问题标题】:Not sure why I'm getting an InvalidCastException不知道为什么我会收到 InvalidCastException
【发布时间】:2012-06-24 19:01:24
【问题描述】:

我收到了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&lt;IList&lt;string&gt;&gt;(TriedIDList_KeyName, TriedIDList_Default)和AddOrUpdateValue(TriedIDList_KeyName, value)是微软推荐的常用方法;你可以找到完整的代码here。

编辑:我在这一行遇到异常:

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

【问题讨论】:

  • 在哪里你得到了异常?哪条线?
  • 如果您逐步通过调试器来识别产生错误的特定行,这将非常有帮助。
  • 对不起,我忘记写了。此处引发异常: settings.TryGetValue>("TriedIDList", outriedIDList);

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


【解决方案1】:

您正在将ObservableCollection&lt;Recipe&gt; 添加到您的settings:

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

但是你正在读回IList&lt;string&gt;,这显然是一种不同的类型:

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

您对triedIDList 的声明如下所示:

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

首先,选择一种类型,然后在所有这些地方使用完全相同的类型(即使您认为这不是绝对必要的),然后查看InvalidCastException 是否消失。

【讨论】:

  • 我会进一步建议您建立一个小型沙箱项目并运行一些您自己的实验,以查看泛型类型(可能还有数组!)允许哪些类型的转换,以及哪些不是。这总是有用的知识! ;)
  • 我会的,谢谢你的建议!再次感谢您解决了我的异常问题!
猜你喜欢
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 2019-09-09
  • 1970-01-01
  • 2023-01-02
  • 2017-11-23
相关资源
最近更新 更多