c# - 如何在 View 状态中存储从字典继承的类的实例?

标签 c# asp.net dictionary viewstate webpage

在网页中,我将 Dictionary 存储在 ViewState 中:

Dictionary<string, string> items = new Dictionary<string, string>();
ViewState["items"] = items;

效果很好。但是,出于某些原因,我想使用自己的类而不是直接使用 Dictionary :

class MyDictionary : Dictionary<string, string> 
{
   ... 
}
MyDictionary items = new MyDictionary();
ViewState["items"] = items;

它没有按预期工作。 ASP.NET 提示的事实

MyDictionary is not marked serializable

没关系,因为类属性不会被继承。所以我改变了我的代码:

[Serializable]
class MyDictionary : Dictionary<string, string> { ... }

但如果我这样做,我会收到另一条错误消息,这次是在页面回发之后:

The state information is invalid for this page and might be corrupted.
System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream)

如果 viewstate 可以序列化 Dictionary,为什么它不适用于从它继承的类?如何实现?

最佳答案

您的类需要一个反序列化构造函数。

class MyDictionary : Dictionary<string, string> 
{
   public MyDictionary (){ }
   protected MyDictionary (SerializationInfo info, 
                           StreamingContext ctx) : base(info, ctx) { }
}

如果你查看一个字典类,它需要这个来反序列化。

protected Dictionary(SerializationInfo info, StreamingContext context);

用测试页试了一下,效果很好。

关于c# - 如何在 View 状态中存储从字典继承的类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12174507/

相关文章:

javascript - 在 Django 中将字符串转换为 Javascript 中的字典列表

python - 访问 Python 字典中的 Unicode 值

dictionary - 检查 map 是否是另一张 map 的子集

c# - PRISM:如何将 View 模型添加到区域并自动创建 View ?

c# - 如何避免重复的 Cursor.Current 语句?

c# - 通过 View 上的按钮运行方法(ASP.NET MVC)

.net - 我在哪里可以看到 ASP.NET 2.0 Web 项目中的引用和 Web 引用列表

asp.net - 在 Gridview 中为一列添加汇总行

c# - Unity,编辑器时间脚本,在游戏对象上添加到场景事件

C#。执行 if( a == (b or c or d))。可能吗?