【问题标题】:Unable to cast object from viewstate to collection无法将对象从视图状态转换为集合
【发布时间】:2014-11-22 06:47:28
【问题描述】:

我正在存储List<KeyValuePair<string, bool>> 的集合 在 ViewState 中,当我尝试将其转换回 List<KeyValuePair<string, bool>> 时会出现问题 错误状态

无法转换类型为“System.Collections.Generic.Dictionary2[System.String,System.Boolean]' to type 'System.Collections.Generic.List1[System.Collections.Generic.KeyValuePair`2[System.String,System.Boolean]]”的对象。

那么如何将我的键值列表从 ViewState 转换回来?

我的代码行是:

List<KeyValuePair<string, bool>> myObject = (List<KeyValuePair<string, bool>>)ViewState["listOutputWords"];

【问题讨论】:

  • 请粘贴您尝试过的代码??
  • List> myObject = (List>)ViewState["listOutputWords"];
  • 您在ViewState["listOutputWords"] 中输入了什么?同时显示完整的异常数据。
  • 我添加了完整的例外
  • 我认为您将KeyValuePair&lt;string, bool&gt; 保存在ViewState["listOutputWords"]

标签: c# asp.net .net collections viewstate


【解决方案1】:

试试这个:-

KeyValuePair<string, bool> myObject = (KeyValuePair<string, bool>)ViewState["listOutputWords"];

正如编译器明确提到的,您的 ViewState 持有一个通用的 DictionaryString,Bool,但您试图将其转换为错误的字典列表。

【讨论】:

    【解决方案2】:

    基于例外情况,您将Dictionary&lt;string, bool&gt; 保存在ViewState 中。如果你真的需要List&lt;KeyValuePair&lt;string, bool&gt;&gt;,试试:

    List<KeyValuePair<string, bool>> myObject = ((Dictionary<string, bool>)ViewState["listOutputWords"]).ToList();
    

    或者您可以将其反序列化为字典并使用它:

    Dictionary<string, bool> myObject = (Dictionary<string, bool>)ViewState["listOutputWords"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多