这里是新来的。我在做一个基于控制台的RPG。进展得很顺利,但我需要找出如何挽救比赛。我猜有一种方法可以将我的应用程序中的变量保存到一个文本文件中,当应用程序再次运行时,该文件可以用来加载变量。不幸的是,我不知道从哪里开始。
此外,我需要一种方式去到一个点的代码时,加载一个保存文件。
我的一些变量包括:
int xCoordinate, yCoordinate, hp, hpmax, level;
任何示例代码都将非常感激。
将一些变量写入文本文件很简单:
TextWriter tw = new StreamWriter("SavedGame.txt");
// write lines of text to the file
tw.WriteLine(xCoordinate);
tw.WriteLine(yCoordinate);
// close the stream
tw.Close();
然后读回:
// create reader & open file
TextReader tr = new StreamReader("SavedGame.txt");
// read lines of text
string xCoordString = tr.ReadLine();
string yCoordString = tr.ReadLine();
//Convert the strings to int
xCoordinate = Convert.ToInt32(xCoordString);
yCoordinate = Convert.ToInt32(yCoordString);
// close the stream
tr.Close();
您可以将变量保存到XML文件中,并在下一次启动时加载它们,这一过程称为序列化。这里有一个帮助器类,它可以将大多数C#对象(包括列表,但不包括字典)序列化和反序列化到XML文件。
如果只有几个值要传输到下一个控制台应用程序,则可以使用命令行参数或管道。
您可以使用二进制序列化相当容易地完成这一任务。首先,创建一个包含所有要编写的变量的类:
[Serializable]
class Data
{
int x;
int y;
}
然后按如下方式使用:
Data data = new Data();
//Set variables inside data here...
// Save data
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = File.OpenWrite("C:\\Temp\\bin.bin"))
{
formatter.Serialize(stream, data);
}