使用FormatterServices 类序列化或反序列化
如果放一个[Serializable]标签就可以实现自动序列化,我想我不会神经到自己自定义实现序列化.
项目中遇到的问题,Mark下.
引用下MSDN的话:
FormatterServices 类来正确地序列化或反序列化符合以下条件的对象:基类未实现 ISerializable,但派生类实现了该接口。
如果放一个[Serializable]标签就可以实现自动序列化,我想我不会神经到自己自定义实现序列化.
项目中遇到的问题,Mark下.
引用下MSDN的话:
FormatterServices 类来正确地序列化或反序列化符合以下条件的对象:基类未实现 ISerializable,但派生类实现了该接口。
改抄了一个MSDN类:
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Reflection;
namespace ecl.Common.Comm
{
/// <summary>
/// 自定义序列化类
/// 详见: ms-help://MS.MSDNQTR.v90.chs/fxref_mscorlib/html/8596f308-b593-d44a-4f16-420430e21302.htm
/// 08/9/23 created by solo
/// </summary>
public class BinarySerializeHelper
{
public static void Serialize(object obj, SerializationInfo info, StreamingContext context)
{
// 获取指定类的所有可序列化成员
Type thisType = obj.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
// Serialize the base class's fields to the info object.
for (Int32 i = 0; i < mi.Length; i++)
{
// Skip this field if it is marked NonSerialized.
if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;
// Get the value of this field and add it to the SerializationInfo object.
info.AddValue(mi[i].Name, ((FieldInfo)mi[i]).GetValue(obj));
}
}
public static void Deserialize(object obj, SerializationInfo info, StreamingContext context)
{
Type thisType = obj.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
// 反序列化对象
for (Int32 i = 0; i < mi.Length; i++)
{
// For easier coding, treat the member as a FieldInfo object
FieldInfo fi = (FieldInfo)mi[i];
// Skip this field if it is marked NonSerialized.
if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;
// Get the value of this field from the SerializationInfo object.
fi.SetValue(obj, info.GetValue(fi.Name, fi.FieldType));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Reflection;
namespace ecl.Common.Comm
{
/// <summary>
/// 自定义序列化类
/// 详见: ms-help://MS.MSDNQTR.v90.chs/fxref_mscorlib/html/8596f308-b593-d44a-4f16-420430e21302.htm
/// 08/9/23 created by solo
/// </summary>
public class BinarySerializeHelper
{
public static void Serialize(object obj, SerializationInfo info, StreamingContext context)
{
// 获取指定类的所有可序列化成员
Type thisType = obj.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
// Serialize the base class's fields to the info object.
for (Int32 i = 0; i < mi.Length; i++)
{
// Skip this field if it is marked NonSerialized.
if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;
// Get the value of this field and add it to the SerializationInfo object.
info.AddValue(mi[i].Name, ((FieldInfo)mi[i]).GetValue(obj));
}
}
public static void Deserialize(object obj, SerializationInfo info, StreamingContext context)
{
Type thisType = obj.GetType();
MemberInfo[] mi = FormatterServices.GetSerializableMembers(thisType, context);
// 反序列化对象
for (Int32 i = 0; i < mi.Length; i++)
{
// For easier coding, treat the member as a FieldInfo object
FieldInfo fi = (FieldInfo)mi[i];
// Skip this field if it is marked NonSerialized.
if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;
// Get the value of this field from the SerializationInfo object.
fi.SetValue(obj, info.GetValue(fi.Name, fi.FieldType));
}
}
}
}
然后对于要自定义序列化的玩意Manage这样搞下就OK了.这个Demo也是MSDN的
Code
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Security.Permissions;
using ecl.Common.Comm;
// 基类Person 可序列
[Serializable]
public class Person
{
private String title;
public Person(String title)
{
this.title = title;
}
public override String ToString()
{
return String.Format("{0}", title);
}
}
// Employee 继承Person并可序列化
[Serializable]
public class Employee : Person
{
private String title;
public Employee(String title)
: base("Person")
{
this.title = title;
}
public override String ToString()
{
return String.Format("{0} -> {1}", title, base.ToString());
}
}
// Manager 可序列化并继承ISerializable
[Serializable]
public class Manager : Employee, ISerializable
{
private String title;
private String name;
public Manager()
: base("Employee")
{
this.title = "Manager";
}
public Manager(string _name)
: base("Employee")
{
this.title = "Manager";
this.name = _name;
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
//序列化对象中你需要的元素
BinarySerializeHelper.Serialize(this, info, context);
DisplaySerializationInfo(info);
}
private void DisplaySerializationInfo(SerializationInfo info)
{
SerializationInfoEnumerator e = info.GetEnumerator();
Console.WriteLine("Values in the SerializationInfo:");
while (e.MoveNext())
{
Console.WriteLine("Name={0}, ObjectType={1}, Value={2}", e.Name, e.ObjectType, e.Value);
}
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
protected Manager(SerializationInfo info, StreamingContext context)
: base(null)
{
// 反序列化构造对象元素
BinarySerializeHelper.Deserialize(this, info, context);
}
public override String ToString()
{
return String.Format("{0} -> {1}", title, base.ToString());
}
}
public sealed class App
{
public static void Main()
{
Run();
Console.ReadLine();
}
public static void Run()
{
using (Stream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
Manager m = new Manager("solo");
Console.WriteLine(m.ToString());
formatter.Serialize(stream, m);
stream.Position = 0;
m = (Manager)formatter.Deserialize(stream);
Console.WriteLine(m.ToString());
}
}
}
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using System.Security.Permissions;
using ecl.Common.Comm;
// 基类Person 可序列
[Serializable]
public class Person
{
private String title;
public Person(String title)
{
this.title = title;
}
public override String ToString()
{
return String.Format("{0}", title);
}
}
// Employee 继承Person并可序列化
[Serializable]
public class Employee : Person
{
private String title;
public Employee(String title)
: base("Person")
{
this.title = title;
}
public override String ToString()
{
return String.Format("{0} -> {1}", title, base.ToString());
}
}
// Manager 可序列化并继承ISerializable
[Serializable]
public class Manager : Employee, ISerializable
{
private String title;
private String name;
public Manager()
: base("Employee")
{
this.title = "Manager";
}
public Manager(string _name)
: base("Employee")
{
this.title = "Manager";
this.name = _name;
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
//序列化对象中你需要的元素
BinarySerializeHelper.Serialize(this, info, context);
DisplaySerializationInfo(info);
}
private void DisplaySerializationInfo(SerializationInfo info)
{
SerializationInfoEnumerator e = info.GetEnumerator();
Console.WriteLine("Values in the SerializationInfo:");
while (e.MoveNext())
{
Console.WriteLine("Name={0}, ObjectType={1}, Value={2}", e.Name, e.ObjectType, e.Value);
}
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
protected Manager(SerializationInfo info, StreamingContext context)
: base(null)
{
// 反序列化构造对象元素
BinarySerializeHelper.Deserialize(this, info, context);
}
public override String ToString()
{
return String.Format("{0} -> {1}", title, base.ToString());
}
}
public sealed class App
{
public static void Main()
{
Run();
Console.ReadLine();
}
public static void Run()
{
using (Stream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
Manager m = new Manager("solo");
Console.WriteLine(m.ToString());
formatter.Serialize(stream, m);
stream.Position = 0;
m = (Manager)formatter.Deserialize(stream);
Console.WriteLine(m.ToString());
}
}
}