首页  编辑  

结构系列化处理

Tags: /C#/其他技巧/   Date Created:

using System . Runtime . Serialization . Formatters . Binary;

[ Serializable ]

struct MyStruct

{

    public int intField;

    public string strField;

    public long longField;

}

private void button1_Click( object sender , EventArgs e)

{

    MyStruct vMyStruct = new MyStruct ();

   vMyStruct . intField = 1234 ;

   vMyStruct . strField = "Zswang ;

   vMyStruct . longField = 1234567890 ;

    BinaryFormatter vBinaryFormatter = new BinaryFormatter ();

    FileStream vFileStream = new FileStream ( @"c:\temp\temp.dat" ,

        FileMode . Create, FileAccess . Write);

   vBinaryFormatter . Serialize(vFileStream, vMyStruct);

   vFileStream . Close();

}

private void button2_Click( object sender , EventArgs e)

{

    BinaryFormatter vBinaryFormatter = new BinaryFormatter ();

    FileStream vFileStream = new FileStream ( @"c:\temp\temp.dat" ,

        FileMode . Open, FileAccess . Read);

    MyStruct vMyStruct = ( MyStruct )vBinaryFormatter . Deserialize(vFileStream);

   vFileStream . Close();

    Console . WriteLine( "{0}, {1}, {2}" ,

       vMyStruct . intField, vMyStruct . strField, vMyStruct . longField);

}