c# winform 应用编程代码总结 9
32、基本序列化
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Read();
Write();
}
static void Read()
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
static void Write()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();
// Here's the proof
Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);
Console.Read();
}
}
33、数组与序列化
[STAThread]
static void Main(string[] args){
//
// TODO: 在此处添加代码以启动应用程序
//
PurchaseOrder obj = new PurchaseOrder();
obj.ItemsOrders=new Item[100];
obj.ItemsOrders[0]=new Item();
obj.ItemsOrders[0].ItemID="First";
obj.ItemsOrders[0].ItemPrice=500.25M;
obj.ItemsOrders[1]=new Item();
obj.ItemsOrders[1].ItemID="Second";
obj.ItemsOrders[1].ItemPrice=66.88M;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
formatter = new BinaryFormatter();
stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
obj = (PurchaseOrder)formatter.Deserialize(stream);
stream.Close();
}
[Serializable]
public class PurchaseOrder
{
public Item [] ItemsOrders;
}
[Serializable]
public class Item
{
public string ItemID;
public decimal ItemPrice;
}
34、二进制文件的读写
private const string FILE_NAME = "Test.dat";
private void button1_Click(object sender, System.EventArgs e)
{
FileStream fs;
if (File.Exists(FILE_NAME))
{
fs = new FileStream(FILE_NAME, FileMode.Truncate);
}
else
{
fs = new FileStream(FILE_NAME, FileMode.CreateNew);
}
BinaryWriter w = new BinaryWriter(fs);
w.Write(DateTime.Now.ToString());
w.Write(DateTime.Now.Ticks);
w.Close();
fs.Close();
}
private void button2_Click(object sender, System.EventArgs e)
{
FileStream fs;
fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
BinaryReader r = new BinaryReader(fs);
MessageBox.Show(r.ReadString()+"\n"+r.ReadInt64().ToString());
r.Close();
fs.Close();
}
本系列文章是作者学习《Visual C#.NET 应用编程150例》(源码)心得笔记,欢迎转载,请注明原文地址,如有疑问,可以通过 278250658@qq.com 联系作者本人。
作者:BuildNewApp
出处:http://syxchina.cnblogs.com、 BuildNewApp.com
本文版权归作者、博客园和百度空间共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则作者会诅咒你的。
如果您阅读了我的文章并觉得有价值请点击此处,谢谢您的肯定1。