正如 Matthew Watson 建议的那样,一个好的解决方案是使用 XML 和序列化。
在您的项目中创建一个 xml,并确保其属性设置为 none 用于 Build Action 和 Copy Always 或 Copy if Newer for Copy to Output Directory。
以下是 xml 文件的示例:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfPlayer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Player>
<Name>Jack</Name>
<WinCount>15</WinCount>
<PlayCount>37</PlayCount>
</Player>
<Player>
<Name>John</Name>
<WinCount>12</WinCount>
<PlayCount>27</PlayCount>
</Player>
</ArrayOfPlayer>
现在我们将使用这个 XML 将其反序列化为玩家列表。我在下面有一个用于序列化的辅助类。您将读取 XML 文件内容并将其传递给 Deserialize 方法,如图所示。当您希望保存 Players 列表时,将列表传递给 Serializer 并保存回您的文件。
序列化器帮助类:
public static class Serializer
{
public static string SerializeObject(object objectToSerialize)
{
XmlSerializer x = new XmlSerializer(objectToSerialize.GetType());
StringWriter writer = new StringWriter();
x.Serialize(writer, objectToSerialize);
return writer.ToString();
}
public static T DeserializeObject<T>(string serializedObject)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
StringReader reader = new StringReader(serializedObject);
return (T)xs.Deserialize(reader);
}
}
使用类反序列化:
//Change this as needed to read your XML file.
string playersXML = File.ReadAllText(@"./Players.xml");
List<Player> players = Serializer.DeserializeObject<List<Player>>(playersXML);
使用类序列化和保存列表:
string newPlayersXML = Serializer.SerializeObject(players);
//Change this as needed to point to the XML location
File.WriteAllText(@"./Players.xml", newPlayersXML);
最后是 Player 类:
public class Player
{
public string Name { get; set; }
public int WinCount { get; set; }
public int PlayCount { get; set; }
}
您将在代码中根据需要使用您的 Player 类和列表。