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

c#
570
2024/1/21 9:47:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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#数据序列化方法,根据实际需求选择合适的方法即可。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#常用的加密算法之一 MD5