【问题标题】:How to store an instance of a class that inherits from dictionary in the viewstate?如何在视图状态中存储从字典继承的类的实例?
【发布时间】:2012-08-23 20:39:54
【问题描述】:

在网页中,我将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 未标记为可序列化

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

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

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

此页面的状态信息无效,可能已损坏。
System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream)

如果 viewstate 可以序列化 Dictionary,为什么它不适用于从它继承的类?如何使这项工作?

【问题讨论】:

标签: c# asp.net dictionary viewstate webpage


【解决方案1】:

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

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

如果您查看字典类,它需要反序列化。

protected Dictionary(SerializationInfo info, StreamingContext context);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2019-12-16
    • 1970-01-01
    相关资源
    最近更新 更多