using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace C16_5
{
///
///自行訂議序列化類別
///
[Serializable]
public class TestAttributeSerializable
{
public string a = "HelloWorld";
//序列化時叫用
[OnSerializing]
internal void OnSerializing(StreamingContext context)
{
a = a.ToLower();
}
//反序列化時叫用
[OnDeserialized]
internal void OnDeserialized(StreamingContext contest)
{
a = a.ToUpper();
}
}
public class Test
{
///
///BinaryFormatter 進行序列化
///
public void DoSerialize()
{
TestAttributeSerializable test = new TestAttributeSerializable();
Stream stem = File.Open("c:\\TestAttributeSerializable.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stem,test);
stem.Close();
Console.WriteLine(test.a);
}
///
///BinaryFormatter 進行反序列化
///
public void DoDeserialize()
{
Stream steam = File.Open("c:\\TestAttributeSerializable.dat",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
TestAttributeSerializable test = (TestAttributeSerializable)bf.Deserialize(steam);
steam.Close();
Console.WriteLine(test.a);
}
public static void Main()
{
TestAttributeSerializable test = new TestAttributeSerializable();
Console.WriteLine("原始資料{0}",test.a);
Test test1 = new Test();
Console.WriteLine("序列化後數據:");
test1.DoSerialize();
Console.WriteLine("反序列化數據:");
test1.DoDeserialize();
}
}
}
沒有留言:
張貼留言