[Serializable] 是 .NET 框架中的一个特性(Attribute),用于标记一个类、结构体、枚举或委托可以被序列化。序列化是将对象的状态转换为可以存储或传输的格式(如二进制、XML 或 JSON)的过程,以便在需要时可以重新创建该对象。
主要用途:
持久化存储:将对象的状态保存到文件或数据库中,以便后续恢复。
跨进程或跨机器传输:在分布式系统中,将对象通过网络传输到其他进程或机器。
深拷贝对象:通过序列化和反序列化实现对象的深拷贝。
如何使用:
在类、结构体、枚举或委托上添加 [Serializable] 特性,即可使其支持序列化。例如:
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
序列化示例:
以下是一个将对象序列化为二进制格式并保存到文件的示例:
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()
{
// 创