c#中的基本序列化与反序列化
先定义一个能被序列化和反序列化的结构体和类。
[Serializable] //这个必须的
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
序列化
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();
反序列化
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();
需要引用的名字空间有
using System.Runtime.Serialization;
//using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;
以前以为很难,今天才发现很简单,不过还有些高级的应用,比如选择性的序列化等等。C#里面的东西太多了。用的时候再学。

浙公网安备 33010602011771号