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}");
}
}
}
类定义:
Person
类被标记为 [Serializable]
,表示它可以被序列化。Person
类包含两个属性:Name
和 Age
。序列化:
BinaryFormatter
对象将 Person
对象序列化到文件 person.dat
中。Serialize
方法将对象的状态保存到流中。反序列化:
BinaryFormatter
对象从文件 person.dat
中读取并还原 Person
对象。Deserialize
方法从流中读取对象的状态并创建一个新的对象实例。注意事项:
BinaryFormatter
已经被标记为过时,建议在新项目中使用其他序列化方法(如 JSON 或 XML)。System.Text.Json
或 Newtonsoft.Json
。上一篇:c#全局变量
下一篇:c# 注释
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站