static void Main_End(string[] args) { BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); ss.AddSurrogate(typeof(StringPlate), bf.Context, new StringClassSurrogate()); //通过SurrogateSelector实例告诉序列化器使用我的代理实例去序列化StringPlate类型 bf.SurrogateSelector = ss; StringPlate sp = new StringPlate("ahahahplate"); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, sp); ms.Position = 0; //注意在这里, 一个不是序列化类型的StringPlate类型, 被序列化成了一个不同的类型StringPlateEndWithQIQIQI //这是通过序列化Surrogate实现的 StringPlateEndWithQIQIQI sq = (StringPlateEndWithQIQIQI)bf.Deserialize(ms); sq.Log(); }
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { StringPlateEndWithQIQIQI sq = new StringPlateEndWithQIQIQI(info.GetString("Content")); return(sq); }