溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#中序列化與反序列化怎樣操作

發布時間:2024-12-23 11:46:19 來源:億速云 閱讀:146 作者:小樊 欄目:編程語言

在C#中,序列化和反序列化是將對象轉換為字節流以便存儲或傳輸,以及從字節流還原為對象的過程。這里是一個簡單的示例,展示了如何使用C#內置的序列化和反序列化方法。

首先,我們需要創建一個簡單的類,例如Person

using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

接下來,我們將演示如何序列化和反序列化這個類。

序列化

要將對象序列化為字節流,我們可以使用BinaryFormatter類。以下是一個示例:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class SerializeDeserializeExample
{
    public static void Main()
    {
        Person person = new Person { Name = "John Doe", Age = 30 };

        // 序列化對象
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, person);

            // 將字節流保存到文件
            File.WriteAllBytes("person.bin", memoryStream.ToArray());
        }
    }
}

反序列化

要從字節流中反序列化對象,我們可以使用相同的BinaryFormatter類。以下是一個示例:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class SerializeDeserializeExample
{
    public static void Main()
    {
        // 從文件中讀取字節流
        byte[] bytes = File.ReadAllBytes("person.bin");

        // 反序列化對象
        using (MemoryStream memoryStream = new MemoryStream(bytes))
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            Person deserializedPerson = (Person)binaryFormatter.Deserialize(memoryStream);

            Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
        }
    }
}

請注意,BinaryFormatter已在.NET Core 3.0及更高版本中棄用。作為替代方案,您可以使用Json.NET(現在稱為Newtonsoft.Json)或System.Text.Json庫進行序列化和反序列化。以下是使用System.Text.Json的示例:

首先,安裝System.Text.Json庫:

dotnet add package System.Text.Json

然后,使用以下代碼進行序列化和反序列化:

using System;
using System.IO;
using System.Text.Json;

public class SerializeDeserializeExample
{
    public static void Main()
    {
        Person person = new Person { Name = "John Doe", Age = 30 };

        // 序列化對象
        string json = JsonSerializer.Serialize(person);
        File.WriteAllText("person.json", json);

        // 反序列化對象
        string deserializedJson = File.ReadAllText("person.json");
        Person deserializedPerson = JsonSerializer.Deserialize<Person>(deserializedJson);

        Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
    }
}

這將使用System.Text.Json庫進行序列化和反序列化,而不是已棄用的BinaryFormatter類。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女