C# Serialization(序列化)
什么是Serialization?
将Object存储为数据(类似于游戏存档)
逆过程即 De-serialization,将数据转化为 Object (类似于游戏读档)
为什么要序列化?
把之前杂乱的数据排列,成为一个有序的数据,方便保存
C# Serialization 运用
假设我们有一个Class叫做Game Data,记录了一些游戏数据
public clas GameData
{
public int health { get; set;} = 100;
public int attack { get; set;} = 5;
public int defense { get; set;] = 4;
}
之后我们创建了一个instance:
GameData data = new GameData();
C#提供了很多的序列化方法,这里以XML为例。
然后我们需要保存这个instance – Serialization:
XmlSerializer xmlserializer = new XmlSerializer(typeof(GameData);
StreamWriter sw = new StreamWriter("C:\GameData"); xmlserializer.Serialize(sw, data);
sw.Close();
保存之后的文件
<?xml version="1.0"encoding="utf-8”?>
<GameData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns.xsd="http:/www.w3.org/2001/XMLSchema"
<health>100</health>
<attack>5</attack>
<defense>4</defense>
</Game Data>
- 与 binary format不同, XML 不指明data type(数据类型)
如果我们想要读取保存的文件→ De-Serialization:
XmlSerializer xmlserializer = new XmlSerializer(typeof(GameData);
StreamReader sr = new StreamReader("C:\Game Data");
GameData data = (GameData) xmlserializer.Deserialize(sr);
sr.Close();
[NonSerialized] / [Xmllgnore]
serializing 时,使我们的某个项目不被serialized
public class GameData
{
[Xmllgynore] public int health { get; set;} = 100;
public int attackI get; set; = 5;
public int defense { get; set;} = 4;
}
于是我们经过 serialization 后的文件变成了:
<?xml version="1.0" encoding="utf-8"?>
<GameDat xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "http://www.w3.org/2001/XMLSchema">
<attack>5</lattack>
<defense>4</defense>
</GameData>
[XmlElement]
public class GameData
{
[XmlElement(ElementName = "HP", Order = 3)] public int health { get; set;} = 100;
[XmlElement(ElementName = "ATK", Order = 2)] public int attack { get; set;} = 5;
[XmIElement(ElementName = "DEF", Order = 1)] public int defense { get; set;} = 4;
}
<?xml version="1.0" encoding="utf-8"?> <GameData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <DEF>4</DEF>
<ATK>5</ATK>
<HP>100</HP>
</GameData>
版权声明:本文为qq_22824431原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。