C#二进制序列化实例分析
本文实例讲述了C#二进制序列化的方法。分享给大家供大家参考。具体如下:
usingSystem.Runtime.Serialization.Formatters.Binary;
usingSystem.Runtime.Serialization;
namespaceWebApplication1.Serialize
{
publicpartialclassBinary1:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
//二进制序列化不同于XMLSerializer类,后者只序列化公共字段。
protectedvoidButton1_Click(objectsender,EventArgse)
{
MyObjectobj=newMyObject();
obj.n1=1;
obj.n2=24;
obj.str="SomeString";
IFormatterformatter=newBinaryFormatter();
Streamstream=newFileStream("C:/MyFile.bin",FileMode.Create,FileAccess.Write,FileShare.None);
formatter.Serialize(stream,obj);
stream.Close();
}
[Serializable]
publicclassMyObject
{
publicintn1=0;
publicintn2=0;
publicStringstr=null;
}
protectedvoidButton2_Click(objectsender,EventArgse)
{
IFormatterformatter=newBinaryFormatter();
Streamstream=newFileStream("C:/MyFile.bin",FileMode.Open,FileAccess.Read,FileShare.Read);
MyObjectobj=(MyObject)formatter.Deserialize(stream);
stream.Close();
//Here'stheproof.
Response.Write("n1:{0}"+obj.n1+"<br/>");
Response.Write("n2:{0}"+obj.n2+"<br/>");
Response.Write("str:{0}"+obj.str+"<br/>");
}
//上面所用的BinaryFormatter非常有效,生成了非常简洁的字节流。
//通过该格式化程序序列化的所有对象也可以通过该格式化程序进行反序列化,这使该工具对于序列化将在.NETFramework上被反序列化的对象而言十分理想。
//需要特别注意的是,在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。
//但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。
//如果可移植性是必需的,则转为使用SoapFormatter。
//只需用SoapFormatter代替上面代码中的BinaryFormatter,
//并且如前面一样调用Serialize和Deserialize。此格式化程序为上面使用的示例生成以下输出。
}
}
希望本文所述对大家的C#程序设计有所帮助。