這篇文章主要介紹了C#如何進(jìn)行序列化和反序列化的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇C#如何進(jìn)行序列化和反序列化文章都會(huì)有所收獲,下面我們一起來看看吧。
創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比甌海網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式甌海網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋甌海地區(qū)。費(fèi)用合理售后完善,十余年實(shí)體公司更值得信賴。
首先把需要序列化的類打上[Serializable]特性,如果某個(gè)字段不需要被序列化,就打上[NonSerialized]特性。
[Serializable] public class Meeting { public string _name; [NonSerialized] public string _location; public Meeting(string name, string location) { this._name = name; this._location = location; } }
對(duì)象序列化后需要一個(gè)載體文件,以下的Meeting.binary文件用來存儲(chǔ)對(duì)象的狀態(tài)。
static void Main(string[] args) { Meeting m1 = new Meeting("年終總結(jié)","青島"); Meeting m2; //先序列化 SerializedWithBinaryFormatter(m1,"Meeting.binary"); m2 = (Meeting) DeserializeWithBinaryFormatter("Meeting.binary"); Console.WriteLine(m2._name); Console.WriteLine(m2._location ?? "_location字段沒有被序列化"); Console.ReadKey(); } //序列化 static void SerializedWithBinaryFormatter(object obj, string fileName) { //打開文件寫成流 Stream streamOut = File.OpenWrite(fileName); BinaryFormatter formatter = new BinaryFormatter(); //把對(duì)象序列化到流中 formatter.Serialize(streamOut, obj); //關(guān)閉流 streamOut.Close(); } //反序列化 static object DeserializeWithBinaryFormatter(string fileName) { //打開文件讀成流 Stream streamIn = File.OpenRead(fileName); BinaryFormatter formatter = new BinaryFormatter(); object obj = formatter.Deserialize(streamIn); streamIn.Close(); return obj; }
Meeting.binary文件在bin/debug文件夾中。
如果想對(duì)序列化的過程有更多的控制,應(yīng)該使用ISerializable接口,通過它的GetObjectData方法可以改變對(duì)象的字段值。
[Serializable] public class Location : ISerializable { public int x; public int y; public string name; public Location(int x, int y, string name) { this.x = x; this.y = y; this.name = name; } protected Location(SerializationInfo info, StreamingContext context) { x = info.GetInt32("i"); y = info.GetInt32("j"); name = info.GetString("k"); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("i", x + 1); info.AddValue("j", y + 1); info.AddValue("k", name + "HELLO"); } }
以上,不僅要實(shí)現(xiàn)接口方法GetObjectData,還需要提供對(duì)象的重載構(gòu)造函數(shù),從SerializationInfo實(shí)例中獲取值。
在客戶端:
Location loc1 = new Location(1,2,"qingdao"); Location loc2; //序列化 SerializedWithBinaryFormatter(loc1, "Location.binary"); loc2 = (Location) DeserializeWithBinaryFormatter("Location.binary"); Console.WriteLine(loc2.x); Console.WriteLine(loc2.y); Console.WriteLine(loc2.name); Console.ReadKey();
以上,使用BinaryFormatter類進(jìn)行序列化和反序列化,存儲(chǔ)的文件格式是二進(jìn)制的,例如,打開Meeting.binary文件,我們看到:
有時(shí)候,我們希望文件的格式是xml。
XmlSerializer類進(jìn)行序列化的存儲(chǔ)文件是xml格式。用XmlSerializer類進(jìn)行序列化的類不需要打上[Serializable]特性。
public class Car { [XmlAttribute(AttributeName = "model")] public string type; public string code; [XmlIgnore] public int age; [XmlElement(ElementName = "mileage")] public int miles; public Status status; public enum Status { [XmlEnum("使用中")] Normal, [XmlEnum("修復(fù)中")] NotUse, [XmlEnum("不再使用")] Deleted } }
在客戶端:
//打開寫進(jìn)流 Stream streamOut = File.OpenWrite("Car.xml"); System.Xml.Serialization.XmlSerializer x = new XmlSerializer(car1.GetType()); //序列化到流中 x.Serialize(streamOut, car1); streamOut.Close(); //打開讀流 Stream streamIn = File.OpenRead("Car.xml"); //反序列化 Car car2 = (Car) x.Deserialize(streamIn); Console.WriteLine(car2.type); Console.WriteLine(car2.code); Console.WriteLine(car2.miles); Console.WriteLine(car2.status); Console.ReadKey();
運(yùn)行,打開bin/debug中的Car.xml文件如下:
<?xml version="1.0"?> <Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" model="sedan"> <code>001</code> <mileage>1000</mileage> <status>使用中</status> </Car>
類名Car成了xml的根節(jié)點(diǎn)
打上[XmlAttribute(AttributeName = "model")]特性的字段變成了根節(jié)點(diǎn)的屬性,AttributeName為屬性別名
枚舉項(xiàng)可打上[XmlEnum("使用中")]特性
如果一個(gè)類中包含集合屬性,比如以下的Department類包含一個(gè)類型List<Employee>的集合屬性Employees。
public class Department { public Department() { Employees = new List<Employee>(); } public string Name { get; set; } [XmlArray("Staff")] public List<Employee> Employees { get; set; } } public class Employee { public string Name { get; set; } public Employee() { } public Employee(string name) { Name = name; } }
在客戶端:
class Program { static void Main(string[] args) { var department = new Department(); department.Name = "銷售部"; department.Employees.Add(new Employee("張三")); department.Employees.Add(new Employee("李四")); XmlSerializer serializer = new XmlSerializer(department.GetType()); //打開寫進(jìn)流 Stream streamOut = File.OpenWrite("Department.xml"); serializer.Serialize(streamOut, department); streamOut.Close(); } }
查看bin/debug中的Department.xml文件。
<?xml version="1.0"?> <Department xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>銷售部</Name> <Staff> <Employee> <Name>張三</Name> </Employee> <Employee> <Name>李四</Name> </Employee> </Staff> </Department>
關(guān)于“C#如何進(jìn)行序列化和反序列化”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“C#如何進(jìn)行序列化和反序列化”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享名稱:C#如何進(jìn)行序列化和反序列化
鏈接地址:http://vcdvsql.cn/article10/pejcgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、定制網(wǎng)站、微信公眾號(hào)、網(wǎng)站維護(hù)、移動(dòng)網(wǎng)站建設(shè)、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
營(yíng)銷型網(wǎng)站建設(shè)知識(shí)