序列化/反序列化/序列化事件/加解密
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Data.SqlClient; namespace Serialize { [Serializable] public class Product//:IDeserializationCallback { private string strConn = @"server=.\sqlexpress; database=Northwind;uid=sa;password=123"; [NonSerialized]//NonSerialized只能加在字段上,不能加在属性上,SqlConnection对象无法序列化 private SqlConnection sqlConn; public int id { get; set; } public string Name { get; set; } public double Price { get; set; } public Product(int id) { this.id = id; } public Product() { sqlConn = new SqlConnection(strConn); } public override string ToString() { return string.Format("ID:{0},Name:{1},Price:{2},\nConn:{3}", id, Name, Price, sqlConn == null ? "Null" : sqlConn.ConnectionString); } private string XorString(string s) { char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) chars[i] =Convert.ToChar( byte.MaxValue - chars[i]); return new string(chars); } [OnSerializing]//在序列化开始事件中调用此方法,自动 void OnSerializing(StreamingContext context) { Console.WriteLine("OnSerializing"); strConn = XorString(strConn); } [OnSerialized]//序列化完成后调用此方法 void OnSerialized(StreamingContext context) { Console.WriteLine("OnSerialized"); strConn = XorString(strConn); } [OnDeserializing]//相当于无参数构造函数,反序列化时初始化对象 void OnDeserializing(StreamingContext context) { Console.WriteLine("OnDerializing"); } [OnDeserialized]//反序列化完成后调用此方法 void OnDeserialized(StreamingContext context) { Console.WriteLine("OnDerialized"); strConn = XorString(strConn); sqlConn = new SqlConnection(strConn); } //反序列化不会调用对象的构造函数,反序列化会自动调用此函数完成对象的状态 public void OnDeserialization(object sender) { Console.WriteLine("OnDerializing"); sqlConn = new SqlConnection(strConn); } } public class MyClass { public static void SerializeWrite() { IFormatter formatter = new BinaryFormatter(); formatter = new SoapFormatter(); Product product = new Product() {id=188, Name = "iPad Mini4", Price = 3698.5f }; System.IO.Stream fs = System.IO.File.OpenWrite(@".\product.bin"); formatter.Serialize(fs, product); fs.Dispose(); } public static void SerializeRead() { IFormatter formatter = new BinaryFormatter(); formatter = new SoapFormatter(); System.IO.Stream stream = System.IO.File.OpenRead(@".\product.bin"); Product product = (Product)formatter.Deserialize(stream); stream.Dispose(); Console.WriteLine(product); } public static void Main() { //SerializeWrite(); SerializeRead(); Console.ReadKey(); } } }