C# 中的序列化
1
/*****************序列化与反序列化***************
2
* 好文:http://www.cnblogs.com/chjw8016/archive/2008/02/23/1078204.html
3
* 1.把对象转换为字节序列的过程称为对象的序列化。
4
* 2.把字节序列恢复为对象的过程称为对象的反序列化。
5
* 3.最简单的方法是使用 Serializable 属性对类进行标记
6
* 4.IFormatter提供序列化的接口
7
************************************************/
8
using System;
9
using System.Data;
10
using System.Configuration;
11
using System.Web;
12
using System.Web.Security;
13
using System.Web.UI;
14
using System.Web.UI.WebControls;
15
using System.Web.UI.WebControls.WebParts;
16
using System.Web.UI.HtmlControls;
17
18
///
19
/// MyObject 的摘要说明
20
///
21
[Serializable]
22
public class MyObject
23
{
24
public int n1 = 0;
25
public int n2 = 0;
26
public string str = null;
27
public MyObject()
28
{
29
//
30
// TODO: 在此处添加构造函数逻辑
31
//
32
}
33
}
34
Default.cs
35
36
using System;
37
using System.Data;
38
using System.Configuration;
39
using System.Web;
40
using System.Web.Security;
41
using System.Web.UI;
42
using System.Web.UI.WebControls;
43
using System.Web.UI.WebControls.WebParts;
44
using System.Web.UI.HtmlControls;
45
46
using System.IO;
47
using System.Runtime.Serialization;
48
using System.Runtime.Serialization.Formatters.Binary;
49
50
public partial class _Default : System.Web.UI.Page
51
{
52
protected void Page_Load(object sender, EventArgs e)
53
{
54
//FuncSerialize();
55
FuncDeserialize();
56
}
57
///
58
/// 序列化,把对象序列化为一个文件
59
///
60
private void FuncSerialize()
61
{
62
MyObject obj = new MyObject();
63
obj.n1 = 1;
64
obj.n2 = 24;
65
obj.str = "字符串";
66
IFormatter formatter = new BinaryFormatter();
67
Stream stream = new FileStream(@"c:\MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
68
formatter.Serialize(stream, obj);
69
stream.Close();
70
}
71
///
72
/// 反序列化,把文件化为一个对象
73
///
74
private void FuncDeserialize()
75
{
76
IFormatter formatter = new BinaryFormatter();
77
Stream stream = new FileStream(@"c:\MyFile.bin", FileMode.Open,
78
FileAccess.Read, FileShare.Read);
79
MyObject obj = (MyObject)formatter.Deserialize(stream);
80
stream.Close();
81
this.Title = obj.str;
82
}
83
}
84

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!