图1.1-1

基本序列化的唯一要求是对象必须应用 SerializableAttribute 特性。 NonSerializedAttribute 可用于禁止序列化特定字段。
1 [Serializable] //将类标记为可序列化
2 public class Coupon : INotifyPropertyChanged
3 {
4 public decimal Amount { get; set; }
5
6 public float InterestRate { get; set; }
7
8 public int Term { get; set; }
9
10 private string _name;
11
12 public string Name
13 {
14 get { return _name; }
15 set
16 {
17 _name = value;
18 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Customer"));
19 }
20 }
21
22 [field: NonSerialized()] //将可序列化的类中的某字段标记为不被序列化
23 public event PropertyChangedEventHandler PropertyChanged;
24
25 public Coupon(decimal amount, float interestRate, int term, string name)
26 {
27 Amount = amount;
28 InterestRate = interestRate;
29 Term = term;
30 _name = name;
31 }
32 }
1 static void Main(string[] args)
2 {
3 const string fileName = @"demo1.txt";
4 var coupon = new Coupon(10000, 0.2f, 1, "反骨仔");
5
6 using (var stream = File.Create(fileName))
7 {
8 var deserializer = new BinaryFormatter(); //二进制格式序列化器
9 deserializer.Serialize(stream, coupon); //序列化对象到文件中
10 }
11 }

图2-1
现在尝试反序列化,看看与之前 Coupon 对象的值是否一致。
1 static void Main(string[] args)
2 {
3 const string fileName = @"demo1.txt";
4 //var coupon = new Coupon(10000, 0.2f, 1, "反骨仔");
5
6 //判断该文件是否存在
7 if (!File.Exists(fileName))
8 {
9 return;
10 }
11
12 using (var stream = File.OpenRead(fileName))
13 {
14 var deserializer = new BinaryFormatter(); //二进制序列化器
15 var coupon = deserializer.Deserialize(stream) as Coupon; //反序列化
16
17 if (coupon == null)
18 {
19 return;
20 }
21
22 Console.WriteLine($"{nameof(Coupon)}:");
23 Console.WriteLine($" {nameof(coupon.Amount)}: {coupon.Amount}");
24 Console.WriteLine($" {nameof(coupon.InterestRate)}: {coupon.InterestRate}%");
25 Console.WriteLine($" {nameof(coupon.Term)}: {coupon.Term}");
26 Console.WriteLine($" {nameof(coupon.Name)}: {coupon.Name}");
27 }
28
29 Console.Read();
30 }

图2-2
1 static void Main(string[] args)
2 {
3 const string fileName = @"demo1.txt";
4 var coupon = new Coupon(10000, 0.2f, 1, "反骨仔");
5
6 using (var stream = File.Create(fileName))
7 {
8 var deserializer = new SoapFormatter(); //Soap 格式化器
9 deserializer.Serialize(stream, coupon); //序列化
10 }
11 }

图2-3
反序列化时也采用 SoapFormatter 即可,结果同图2-2。
var deserializer = new SoapFormatter(); //Soap 格式化器
var coupon = deserializer.Deserialize(stream) as Coupon; //反序列化
【注意】本示例将数据存储到二进制或 SOAP 格式的文件中。不应将这些格式用于敏感数据,如密码或信用卡信息。
【备注】二进制格式对于大多数 Windows 应用程序均适用。但对于 Web 应用程序或 Web 服务,您可能希望使用 SOAP 格式将对象保存到 XML 文件中,以使对象易于共享。
同样,也可以通过 XmlSerializer 将对象序列化保存在 XML 文件。我们可以根据需求选择合适的序列化器,操作基本是一样的。
@hi丶小时候 使用 SerializableAttribute 特性时,是不建议使用自动属性的,序列化后的字段都是多出 k_BackingField<> 17个字符,如果对象很大会浪费一部分流量,建议使用 DataContractAttribute 和 DataMemberAttribute
@梁逸晨 除非对方系统强制要求 SOAP 才能通信,否则该人人抵制这么反人类的东西,建议楼主 JSON 或 Protobuf
原文:http://www.cnblogs.com/zhangxiaolei521/p/5913834.html