UD2SL4——让Dictionary支持序列化和反序列化

  1. 我们没办法修改C#自带的类
  2. 我们可以重写一个类,继承Dictionary​然后让这个类继承序列化拓展接口lXmlSerialzable​
  3. 实现里面的序列化和反序列化规则即可

实现过程

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
public class SerizlizerDictionary<Tkey, TValue> : Dictionary<Tkey, TValue>, IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
//自定义 字典的 反序列化规则
public void ReadXml(XmlReader reader)
{
XmlSerializer keySer = new XmlSerializer(typeof(Tkey));
XmlSerializer valueSer = new XmlSerializer(typeof(TValue));
reader.Read(); //要跳过根节点的头节点
//循环遍历所有节点
while (reader.NodeType != XmlNodeType.EndElement) //判断当前不是元素节点尾节点 进行反序列化
{
Tkey key = (Tkey)keySer.Deserialize(reader); //反序列化键
TValue value = (TValue)valueSer.Deserialize(reader); //反序列化值
this.Add(key, value); //向自己存储这对键值对
}
reader.Read(); //跳过(字典的)根节点的尾节点,避免影响之后数据的读取!
}
//自定义 字典的 序列化规则
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySer = new XmlSerializer(typeof(Tkey));
XmlSerializer valueSer = new XmlSerializer(typeof(TValue));

foreach(KeyValuePair<Tkey, TValue> kv in this)
{
keySer.Serialize(writer, kv.Key);
valueSer.Serialize(writer, kv.Value);
}
}
}
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
public class TestLesson4
{
public int Test1;
public SerizlizerDictionary<int, string> dic;
}

public class Lesson4 : MonoBehaviour
{
TestLesson4 tl4;
void Start()
{
tl4 = new TestLesson4
{
dic = new SerizlizerDictionary<int, string>()
};
tl4.dic.Add(1, "123");
tl4.dic.Add(2, "234");
tl4.dic.Add(3, "345");

string path = Application.persistentDataPath + "/TestLesson4.xml";

using (StreamWriter writer = new StreamWriter(path))
{
XmlSerializer s = new XmlSerializer(typeof(TestLesson4));
s.Serialize(writer, tl4);
}

using (StreamReader reader = new StreamReader(path))
{
XmlSerializer s = new XmlSerializer(typeof(TestLesson4));
tl4 = (TestLesson4)s.Deserialize(reader);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<TestLesson4 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Test1>0</Test1>
<dic>
<int>1</int>
<string>123</string>
<int>2</int>
<string>234</string>
<int>3</int>
<string>345</string>
</dic>
</TestLesson4>