温馨提示×

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

c#
小亿
108
2024-01-31 09:47:44
栏目: 编程语言

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

0