Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 序列化和反序列化

作者:穹上之月   发布日期:2025-06-05   浏览:70

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

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

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Program
{
    static void Main()
    {
        // 创建一个Person对象
        Person person = new Person("Alice", 30);

        // 序列化
        using (FileStream fs = new FileStream("person.dat", FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, person);
            Console.WriteLine("对象已序列化");
        }

        // 反序列化
        using (FileStream fs = new FileStream("person.dat", FileMode.Open))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Person deserializedPerson = (Person)formatter.Deserialize(fs);
            Console.WriteLine($"反序列化后的对象: 名字 = {deserializedPerson.Name}, 年龄 = {deserializedPerson.Age}");
        }
    }
}

解释说明

  1. 类定义:

    • Person 类被标记为 [Serializable],表示它可以被序列化。
    • Person 类包含两个属性:NameAge
  2. 序列化:

    • 使用 BinaryFormatter 对象将 Person 对象序列化到文件 person.dat 中。
    • Serialize 方法将对象的状态保存到流中。
  3. 反序列化:

    • 使用 BinaryFormatter 对象从文件 person.dat 中读取并还原 Person 对象。
    • Deserialize 方法从流中读取对象的状态并创建一个新的对象实例。
  4. 注意事项:

    • BinaryFormatter 已经被标记为过时,建议在新项目中使用其他序列化方法(如 JSON 或 XML)。
    • 在实际应用中,应考虑使用更安全和现代的序列化库,例如 System.Text.JsonNewtonsoft.Json

上一篇:c#全局变量

下一篇:c# 注释

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站