using System;
using System.Runtime.Serialization;
//子类负责父类的序列化(如果父类未实现序列化)
namespace ConsoleApp_SerializableParentByChild
{
class Program
{
static void Main(string[] args)
{
//子类负责父类的序列化(父类未实现序列化的情况)
Employee employeeA = new Employee() { Name = "Zhang", Salary = 10000 };
BinarySerializer.SerializeToFile(employeeA, @"c:", "person.txt");
Employee employeeACopy = BinarySerializer.DeserializeFromFile<Employee>(@"c:person.txt");
Console.WriteLine("姓名:{0}", employeeACopy.Name);
Console.WriteLine("薪水:{0}", employeeACopy.Salary);
Console.ReadKey();
}
}
#region 父类未序列化的情况
[Serializable]
class Employee : Person, ISerializable
{
//父类Person未实现序列化的情况,由子类处理
public int Salary { get; set; }
public Employee()
{ }
/// <summary>
/// 取出信息(在反序列化时调用)
/// </summary>
protected Employee(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");//取父类的Name
Salary = info.GetInt32("Salary");
}
/// <summary>
/// 给属性赋值(在序列化时调用)
/// </summary>
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Salary", Salary);
info.AddValue("Name", Name);//序列化父类的Name
}
}
class Person
{
public string Name { get; set; }
}
#endregion
#region 父类序列化的情况
//[Serializable]
//class Person : ISerializable
//{
// public string Name { get; set; }
// public Person() { }
// protected Person(SerializationInfo info, StreamingContext context)
// {
// Name = info.GetString("Name");
// }
// public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
// {
// info.AddValue("Name", Name);
// }
//}
//[Serializable]
//class Employee : Person, ISerializable
//{
// //父类Person实现序列化的情况,子类只需调用base.GetObjectData即可
// public int Salary { get; set; }
// public Employee()
// {
// }
// /// <summary>
// /// 取出信息(在反序列化时调用)
// /// </summary>
// protected Employee(SerializationInfo info, StreamingContext context)
// {
// Salary = info.GetInt32("Salary");
// Name = info.GetString("Name");
// }
// /// <summary>
// /// 给属性赋值(在序列化时调用)
// /// </summary>
// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
// {
// base.GetObjectData(info, context);
// info.AddValue("Salary", Salary);
// }
//}
#endregion
}
工具类:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApp_SerializableParentByChild
{
public class BinarySerializer
{
/// <summary>
/// 将类型序列化为字符串
/// </summary>
public static string Serialize<T>(T t)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// 将类型序列化为文件
/// </summary>
public static void SerializeToFile<T>(T t, string path, string fullname)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fullPath = string.Format(@"{0}{1}", path, fullname);
using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
stream.Flush();
}
}
/// <summary>
/// 将字符串反序列化为类型
/// </summary>
public static TResult Deserialize<TResult>(string s) where TResult : class
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);
using (MemoryStream stream = new MemoryStream(bs))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
/// <summary>
/// 将文件反序列化为类型
/// </summary>
public static TResult DeserializeFromFile<TResult>(string path) where TResult : class
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
}
}