[英]How to store an instance of a class that inherits from dictionary in the viewstate?
在網頁中,我在ViewState
存儲一個Dictionary
:
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
,為什么它不適用於從它繼承的類? 如何使這項工作?
您需要為您的類設置反序列化構造函數。
class MyDictionary : Dictionary<string, string>
{
public MyDictionary (){ }
protected MyDictionary (SerializationInfo info,
StreamingContext ctx) : base(info, ctx) { }
}
如果你查看一個字典類,它需要這個反序列化。
protected Dictionary(SerializationInfo info, StreamingContext context);
嘗試用測試頁面,它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.