【发布时间】:2015-06-12 22:33:21
【问题描述】:
我是 C# 的新手,我一直在寻找解决这个问题的方法,尽管我尝试的任何方法似乎都不起作用:(
public Form1()
{
InitializeComponent();
File.ReadAllLines(@"C:\Users\Simon\test.txt");
???
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
List<string> newlist = highscores.ConvertAll<string>(x => x.ToString());
File.WriteAllLines(@"C:\Users\Simon\test.txt", newlist);
}
这是我现在的代码,如您所见,我通过将整数转换为字符串并写入它们,成功地将高分(列表)写入文件。现在我必须阅读它们并将它们转换回整数(稍后在我的代码中,玩家通过创建新的高分来添加整数)。我尝试使用 convert 方法,但我所做的一切似乎都不起作用,我不确定我是否应该在这里使用数组,但考虑到我只使用了列表,这会让我感到惊讶。正如我所说,我是编程新手,所以我可以在这方面使用一些帮助:p
编辑更多信息:抱歉信息不足,但高分是一个列表。每次玩家获得新的高分时,都会创建一个新条目,并且最多保持 5 分。这就是我试图进入文本文件的内容,以便在程序运行时可以“保存”和检索高分又开始了。程序启动时,我无法将高分重新添加到列表中。
更多代码: 全局变量
List<int> highscores = new List<int>();
int totaltime = 0;
int timeleft = 3;
列表的工作原理和内容。游戏的目的是躲避尽可能多的方格,如果它相交会发生以下情况。
if (picturebox.Bounds.IntersectsWith(pictureBox1.Bounds))
{
pictureBox1.Location = new Point(668, 580);
pictureBox2.Location = new Point(622, 30);
timer4.Stop();
timer3.Stop();
timer2.Stop();
timer1.Stop();
timer4.Interval = 1000;
label2.Hide();
button1.Enabled = true;
button2.Enabled = true;
MessageBox.Show("You died! You lasted " + totaltime + " seconds.");
if (highscores.Count < 5)
{
highscores.Add(totaltime);
highscores.Sort();
}
else
{
int newscore = totaltime;
int lowestscore = int.MaxValue;
foreach (int score in highscores)
{
if (score < lowestscore)
lowestscore = score;
}
if (newscore > lowestscore)
{
highscores.Remove(lowestscore);
highscores.Add(newscore);
highscores.Sort();
}
}
textBox1.Clear();
for (int n = highscores.Count - 1; n >= 0; n--)
textBox1.AppendText(highscores[n].ToString() + "\n");
totaltime = 0;
timeleft = 3;
label5.Text = "0";
foreach (PictureBox pic in pbspawn)
{
if (pic != pictureBox2)
this.Controls.Remove(pic);
}
pbspawn = new List<PictureBox>();
}
如果还有什么我可以补充说明的,请说出来。
【问题讨论】:
-
查看序列化程序。
NewtonSoft.Json,或Xml.XmlSerializer。 -
欢迎来到 Stack Overflow!有一本关于 C# 编程语言的完整手册。在询问有关语言语法的基本问题之前,您应该先查看它。见C# Programming Guide。详细参考请见C# Reference。
-
请学习包含重现问题所需的所有信息。您甚至没有告诉我们
highscores的数据类型,更不用说向我们展示它是如何定义或填充的。