1.demo:
static Stream MySerialize(object o)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, o);
return stream;
}
static object MyDeserialize(Stream stream)
{
BinaryFormatter bf = new BinaryFormatter();
return bf.Deserialize(stream);
}
2. 序列化应用
//深拷贝
static object DeepCloneBySerialize(object o)
{
BinaryFormatter bf = new BinaryFormatter();
bf.Context = new StreamingContext(StreamingContextStates.Clone);
MemoryStream stream = new MemoryStream();
bf.Serialize(stream,o);
stream.Position = 0;
return bf.Deserialize(stream);
}
3. 使类型可序列化:为类型定制SerializableAttribute;
注意:如果标记了类型,则类型下的字段都默认继承了这一个特性,但是不会被派生类继承:
[Serializable]
class Person { }
class Employee : Person { } Person可以序列化,但是Employee不可以,也需定制Serializable;
[NonSerialized] 将字段(不能是类型)标记为不被序列化。
[OnSerialized]:在反序列化时,格式化器都会检查是否定制了这个特性;如果定制了,就会调用被该特性标记的方法,将可序列化的字段正确设置:
[OnDeserialized]
private void OnDeserialized(StreamingContext context){//….}