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("张三", 30);
// 序列化对象到文件
Serialize(person, "person.dat");
// 反序列化对象从文件
Person deserializedPerson = Deserialize("person.dat");
// 输出反序列化后的对象信息
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
// 序列化方法
static void Serialize(Person person, string filePath)
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
formatter.Serialize(stream, person);
}
}
// 反序列化方法
static Person Deserialize(string filePath)
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
return (Person)formatter.Deserialize(stream);
}
}
}
[Serializable]
属性标记 Person
类,使其可以被序列化。Person
对象,并设置其属性。Serialize
方法使用 BinaryFormatter
进行序列化。Person
对象。Deserialize
方法同样使用 BinaryFormatter
进行反序列化。注意:BinaryFormatter
在 .NET Core 和 .NET 5+ 中已被弃用,建议使用其他序列化方式如 JSON 或 XML 序列化。
上一篇:c# begininvoke
下一篇:c# orm
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站