怎么使用c#进行数据序列化

avatar
作者
筋斗云
阅读量:3

在C#中进行数据序列化有多种方法,其中最常用的是使用BinaryFormatterXmlSerializerDataContractSerializer。下面分别介绍这三种方法的使用方式:

  1. 使用BinaryFormatter进行数据序列化与反序列化:
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary;  [Serializable] public class MyClass {     public int Number { get; set; }     public string Text { get; set; } }  public static void Main() {     MyClass obj = new MyClass() { Number = 1, Text = "Hello, World!" };      // 序列化     BinaryFormatter formatter = new BinaryFormatter();     using (FileStream fileStream = new FileStream("data.bin", FileMode.Create))     {         formatter.Serialize(fileStream, obj);     }      // 反序列化     using (FileStream fileStream = new FileStream("data.bin", FileMode.Open))     {         MyClass deserializedObj = (MyClass)formatter.Deserialize(fileStream);         Console.WriteLine($"Number: {deserializedObj.Number}, Text: {deserializedObj.Text}");     } } 
  1. 使用XmlSerializer进行数据序列化与反序列化:
using System; using System.IO; using System.Xml.Serialization;  [Serializable] public class MyClass {     public int Number { get; set; }     public string Text { get; set; } }  public static void Main() {     MyClass obj = new MyClass() { Number = 1, Text = "Hello, World!" };      // 序列化     XmlSerializer serializer = new XmlSerializer(typeof(MyClass));     using (FileStream fileStream = new FileStream("data.xml", FileMode.Create))     {         serializer.Serialize(fileStream, obj);     }      // 反序列化     using (FileStream fileStream = new FileStream("data.xml", FileMode.Open))     {         MyClass deserializedObj = (MyClass)serializer.Deserialize(fileStream);         Console.WriteLine($"Number: {deserializedObj.Number}, Text: {deserializedObj.Text}");     } } 
  1. 使用DataContractSerializer进行数据序列化与反序列化:
using System; using System.IO; using System.Runtime.Serialization;  [DataContract] public class MyClass {     [DataMember]     public int Number { get; set; }      [DataMember]     public string Text { get; set; } }  public static void Main() {     MyClass obj = new MyClass() { Number = 1, Text = "Hello, World!" };      // 序列化     DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));     using (FileStream fileStream = new FileStream("data.xml", FileMode.Create))     {         serializer.WriteObject(fileStream, obj);     }      // 反序列化     using (FileStream fileStream = new FileStream("data.xml", FileMode.Open))     {         MyClass deserializedObj = (MyClass)serializer.ReadObject(fileStream);         Console.WriteLine($"Number: {deserializedObj.Number}, Text: {deserializedObj.Text}");     } } 

以上是三种常用的C#数据序列化方法,根据实际需求选择合适的方法即可。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!