Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

序列化和反序列化

一、序列化

1.非字符串类型转字节数组


关键类:BitConverter
命名空间:System
主要作用:非字符串类型 和 字节数组 的相互转化

1
2
3
byte[] bytes1 = BitConverter.GetBytes(1);
byte[] bytes2 = BitConverter.GetBytes(1.2f);
byte[] bytes3 = BitConverter.GetBytes(ture);

2.字符串类型转字节数组


关键类:Encoding
命名空间:System.Text
主要作用:将字符串类型和字节数组相互转化,并且决定转化时使用的字符编码类型(建议网络通讯使用 UTF-8)

1
byte[] bytes = Encoding.UTF8.GetBytes("123");

3.类对象转化为二进制

注意:
网络通信中我们不能直接使用数据持久化 2 进制知识点中的 BinaryFormatter2 进制格式化类
因为客户端和服务器使用的语言可能不一样,BinaryFormatter 是 c#的序列化规则,和其它语言之间的兼容性不好
如果使用它,那么其它语言开发的服务器无法对其进行反序列化 ,我们需要自己来处理将类对象数据序列化为字节数组


单纯的转换一个变量为字节数组非常的简单
但是我们如何将一个类对象携带的所有信息放入到一个字节数组中呢


我们需要做以下几步 1. 明确字节数组的容量(注意:在确定字符串字节长度时要考虑解析时如何处理) 2. 申明一个装载信息的字节数组容器 3. 将对象中的所有信息转为字节数组并放入该容器当中(可以利用数组中的 copyTo 方法转存字节数组) CopyTo 方法的第二个参数代表 从容器的第几个位置开始存储

1
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
Class PlayerInfo
{
pulic int lev;
pulic string name;
pulic short atk;
pulic bool sex;


pulic byte[] GetBytes()
{
int indexNum=sizeof(int)+ //lev int类型
sizeof(int)+//代表 name字符串转换成字节数组后 数组的长度
Encoding.UTF8.GetBytes(name).Length +//字符串具体字节数组的长度
sizeof(short)+//atk short类型
sizeof(bool);//sex boo1类型
byte[] playerBytes = new byte[indexNum];
int index=0;//从 playerBytes数组中的第几个位置去存储数据
//等级
BitConverter.GetBytes(lev).copyTo(playerBytes,index);
index += sizeof(int);
//姓名
byte[]strBytes = Encoding.UTF8.GetBytes(name);
//存储的是姓名转换成字节数组后 字节数组的长度
int num=strBytes.Length;
BitConverter.GetBytes(num).copyTo(playerBytes, index);
index += sizeof(int);
//存储字符串的字节数组
strBytes.copyTo(playerBytes, index);
index += num;
//攻击力
BitConverter.GetBytes(info.atk).copyTo(playerBytes, index);
index += sizeof(short);
//性别
BitConverter.GetBytes(info.sex).CopyTo(playerBytes, index);
index += sizeof(bool);
}
}

二、反序列化

1.字节数组转非字符串类型


关键类:BitConverter
命名空间:System
主要作用:除了字符串意外的其他常用类型和字节数组相互转化

1
2
3
4
int i = BitConvert.ToInt32(bytes,0);
//参数一:字节数组
//参数二:从第几位开始转化
//其他类型类似 调用对应api即可

2.字节数组转字符串类型


关键类:Encoding
命名空间:System.Text
主要作用:字符串和字节数组相互转化

1
2
3
4
5
string str = Ecoding.UTF8.GetString(bytes);
string str = Ecoding.UTF8.GetString(bytes,0,bytes.Leght);
//参数一:字节数组
//参数二;从第几位开始转化
//参数三:转化长度

3.将二进制数据转化为一个类对象

1.)获取对应的字节数组

1
2
3
4
//这里以上面的Player类对象为例子
//默认初始化完成
PlayerInfo info = new PlayerInfo();
byte[] playerInfoBytes = info.GetBytes();

2.)将字节数组按照序列化时的顺序进行反序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//等级
int index =0;
info2.lev = BitConverter.ToInt32(playerBytes, index);
index += 4
//姓名的长度
int length = BitConverter.ToInt32(playerBytes, index);
index += 4;
//姓名字符串
info2.name = Encoding.UTF8.GetString(playerBytes, index, length);
index += length;
//攻击力
info2.atk = BitConverter.ToInt16(playerBytes, index);
index += 2;
//性别
info2.sex= BitConverter.ToBoolean(playerBytes, index);
index += 1;

评论