serializable 对象序列化
序列化其实是对象和字符串(文件)之间的互相转换。
二进制序列化
类型前面添加了[serializable]特性的类就是可序列化类型。
SerializableAttribute特性只能应用于引用类型(class)、值类型(struct)、枚举类型(enum)和委托类型(delegate)。
枚举和委托类型总是可序列化的,所以不必显示使用SerializableAttribute特性。
序列化会读取对象的所有字段保存成二进制。
如果必须序列化该对象,则可将 [NonSerialized] 属性应用于存储敏感数据的特定字段。
using System;
var demo = new Demo();
demo.Number = 100;
demo.Text = "hhhhh";
Console.WriteLine(demo.ToString());
var str = SerializerHelper.BinarySerialize(demo);
Console.WriteLine(str);
var aa = SerializerHelper.BinaryDeserialize<Demo>(str);
Console.WriteLine(aa.ToString());
[Serializable]
public class Demo
{
private int _field = DateTime.Now.Millisecond;
public string Test = "Test";
public int Number { get; set; }
public string Text { get; set; }
public override string ToString()
{
return $"({Number}, {Text}) {_field} {Test}";
}
}
public static partial class SerializerHelper
{
/// <summary>
/// 二进制序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string BinarySerialize<T>(T obj)
{
BinaryFormatter serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, obj);
return Convert.ToBase64String(ms.ToArray());
}
}
/// <summary>
/// 二进制反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="txt"></param>
/// <returns></returns>
public static T BinaryDeserialize<T>(string txt)
{
var data = Convert.FromBase64String(txt);
using (var ms = new MemoryStream(data))
{
BinaryFormatter serializer = new BinaryFormatter();
var obj = serializer.Deserialize(ms);
if (obj is T)
{
return (T)obj;
}
}
return default(T);
}
}
XML序列化
var demo = new Demo();
demo.Number = 100;
demo.Text = "hhhhh";
Console.WriteLine(demo.ToString());
str = SerializerHelper.XmlSerialize(demo);
Console.WriteLine(str);
var cc = SerializerHelper.XmlDeserialize<Demo>(str);
Console.WriteLine(cc.ToString());
/// <summary>
/// XML序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string XmlSerialize<T>(T obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, obj, xmlns);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// XML反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="txt"></param>
/// <returns></returns>
public static T XmlDeserialize<T>(string txt)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var sr = new StringReader(txt))
{
var obj = serializer.Deserialize(sr);
if (obj is T)
{
return (T)obj;
}
}
return default(T);
}