在网页中,我将 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/