c#范例,序列化存取类。

可能是我的习惯不好。也可能是我觉得程序员最好的沟通方式就是代码,又或是我太自信自己的代码是很容易看懂的,更或者我认为我写的程序本身就是艺术品。所以,我只想,贴代码:

类定义如下

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace DllTest { [StructLayout(LayoutKind.Explicit)] public class MyClass { [FieldOffset(0)] private double x = 0; [FieldOffset(8)] private double y = 0; [FieldOffset(16)] private double z = 0; [FieldOffset(24)] private int id = 0; public double X { get { return x; } set { x = value; } } public double Y { get { return y; } set { y = value; } } public double Z { get { return z; } set { z = value; } } public int ID { get { return id; } set { id = value; } } public MyClass(double dx, double dy, double dz, int nid) { x = dx; y = dy; z = dz; id = nid; } //反序列化的时候需要用一个无参构造函数 public MyClass() { } } }

读写的例子如下:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.IO; using DllTest; namespace SerializeTest { class Program { static void Main(string[] args) { Console.ReadKey(); } public static void WriteSample() { List<MyClass> datas = new List<MyClass>(); datas.AddRange(new MyClass[] { new MyClass(1, 1, 1, 1), new MyClass(2, 2, 2, 2), new MyClass(3, 3, 3, 3) }); using (FileStream fs = File.OpenWrite(@"c:/position.bin")) { int size = Marshal.SizeOf(typeof(MyClass)); byte[] buffer = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); foreach (MyClass item in datas) { Marshal.StructureToPtr(item, ptr, true); Marshal.Copy(ptr, buffer, 0, size); fs.Write(buffer, 0, size); } Marshal.FreeHGlobal(ptr); } Console.WriteLine("Save complete./r/nPress any key to end program."); } public static void ReadSample() { List<MyClass> datas = new List<MyClass>(); int size = Marshal.SizeOf(typeof(MyClass)); using (FileStream fs = File.OpenRead(@"c:/position.bin")) { if (fs.Length % size != 0) { Console.WriteLine("File size not valid. Maybe error when save file."); } else { IntPtr ptr = Marshal.AllocHGlobal(size); byte[] buffer = new byte[size]; while (fs.Read(buffer, 0, size) == size) { Marshal.Copy(buffer, 0, ptr, size); MyClass obj = Marshal.PtrToStructure(ptr, typeof(MyClass)) as MyClass; if (obj == null) { Console.WriteLine("File load faild."); break; } datas.Add(obj); } //read complete datas.ForEach(m => { Console.WriteLine("id={0} x={1} y={2} z={3}", m.ID, m.X, m.Y, m.Z); }); } } Console.WriteLine("Press any exit program."); Console.ReadKey(); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值