繁体   English   中英

在C#中使用计时器的高分系统

[英]High score system using timer in c#

我正在制作一个高分系统,但是在将新时间与已经保存在文本文件中的时间进行比较时遇到了麻烦。 我可以使用StreamWriter节省时间,但是当我使用StreamRreader读取文件时,我无法将其与新时间进行比较,因为新时间是一个int并且我正在从文本文件字符串中读取计时器。 我试图将字符串更改为int但找不到可行的方法。 先感谢您!

我用来阅读文字的代码:

string[] test = new string[5];

StreamReader SR = new StreamReader(@"test.txt");

for (int i = 0; i < 10; i++)
{
    test[i] = SR.ReadLine();
}

文本文件的内容是什么? 您只能将字符串内容存储在文本文件中,因此您必须先读取文件的内容,然后再读取.Parse或.TryParse才能将字符串转换为所需的类型(例如Int)

实际上,您的代码将引发IndexOutOfRangeException异常,因为您初始化了一个由5个元素组成的字符串数组,但是循环并尝试将元素添加到该数组10次。

目前尚不清楚文本文件中的内容。 因此,这是在文本文件中写入,读取和解析日期时间的简单方法:

        string date = DateTime.Now.ToString();

        // Write the string to a file.
        System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\folder\\test.txt");
        file.WriteLine(date);
        file.Close();

        // Read file
        DateTime dateTime;
        string firstRowFromFile = File.ReadLines("c:\\folder\\test.txt").First();
        if (DateTime.TryParse(firstRowFromFile, out dateTime))
        {
            // right datetime format
        }
        else
        {
            // wrong datetime format
        }

在现实生活中,此代码还应使用try / catch块正确处理异常。

尝试在比较之前解析字符串:

类似的东西:

StreamReader SR = new StreamReader(@"test.txt");

for (int i = 0; i < 10; i++)
{
    test[i] = SR.ReadLine();

    DateTime time = DateTime.ParseExact(test[i], "HH:mm:ss", CultureInfo.InvariantCulture);
}

您可以尝试将ReadLine()的结果转换为int。

Convert.ToInt32(SR.ReadLine);

假设它是您所说的int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM