我尝试序列化FormCollection对象,并根据我研究的内容继承NameObjectCollectionBase,因此它还继承了GetObjectData和ISerializable。这不意味着它是可序列化的吗?
https://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection(v=vs.118).aspx
这是我尝试的一小部分:
BinaryFormatter formatter = new BinaryFormatter();
//Serialize
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, data);
string test = Convert.ToBase64String(stream.ToArray());
Session["test"] = test;
};
//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String((string)Session["test"])))
{
data = (FormCollection) formatter.Deserialize(stream);
}
不幸的是,我得到了这个错误:
System.Runtime.Serialization.SerializationException: Type 'System.Web.Mvc.FormCollection' in Assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral... is not marked as serializable.
因为这是一个密封的类,我无法扩展它并添加[Serializable]属性。
我的问题是:
为什么我不能像这样序列化FormCollection?
我如何序列化/反序列化FormCollection对象?
答案 0 :(得分:2)
它无法像这样序列化,因为它缺少[Serializable]
属性。这意味着这个类的开发人员无意使其可序列化(使用BinaryFormatter
)。它的父类实现ISerializable
并用[Serializable]
标记的事实不会改变任何内容 - 子类可能有它自己的内部细节,如果允许序列化可序列化类的任何后代,它将在序列化期间丢失。
如果你想使用BinaryFormatter
(这可能是也可能不是最好的方式) - 你可以这样做:
BinaryFormatter formatter = new BinaryFormatter();
//Serialize
string serialized;
using (MemoryStream stream = new MemoryStream())
{
// pass FormCollection to constructor of new NameValueCollection
// that way we kind of convert it to NameValueCollection which is serializable
// of course we lost any FormCollection-specific details (if there were any)
formatter.Serialize(stream, new NameValueCollection(data));
serialized = Convert.ToBase64String(stream.ToArray());
};
//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(serialized))) {
// deserialize as NameValueCollection then create new
// FormCollection from that
data = new FormCollection((NameValueCollection) formatter.Deserialize(stream));
}