我正在尝试为C#创建一个库,它将获得列表框中的最大数量。 目前我只是在创建库之前在程序中尝试该方法。我有以下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace SPE16
{
public partial class FormExamStatistics : Form
{
List<double> ExamScores = new List<double>();
double highScore = 0;
public FormExamStatistics()
{
InitializeComponent();
}
private double HighScore(List<double> anyList) //return the highest score
{
return highScore = ExamScores.Max();
}
private void buttonAddFromFile_Click(object sender, EventArgs e)
{
StreamReader reader;
reader = File.OpenText("ExamScores.txt");
while (!reader.EndOfStream)
{
double Scores;
double.TryParse(reader.ReadLine(), out Scores);
ExamScores.Add(Scores);
listBoxScores.Items.Add(Scores);
labelHighScore.Text = highScore.ToString();
}
reader.Close();
/////////////
HighScore(ExamScores);
/////////////
}
}
}
现在,它应该从顶部创建的列表中返回最大值,该列表由文本文件“ExamScores.txt”填充。此文本文件包含60(双)分数,最大数量为120。 最大数量应为120,但返回“0”。
现在我需要首先将其作为方法,以便稍后创建(dll)库。
我做错了什么?
答案 0 :(得分:1)
您需要检查文件,因为.NET Framework设计指南建议使用Try方法。避免异常通常是一个很好的理念
if (value == null)
{
return 0.0;
}
return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider)
请发布您的文件内容
你尝试过,private void buttonAddFromFile_Click(object sender, EventArgs e){
StreamReader reader;
reader = File.OpenText("ExamScores.txt");
while (!reader.EndOfStream){
double Scores;
double.TryParse(reader.ReadLine(), out Scores);
ExamScores.Add(Scores);
listBoxScores.Items.Add(Scores);
labelHighScore.Text = highScore.ToString();
}
reader.Close();
/////////////
HighScore(ExamScores);
/////////////
}
答案 1 :(得分:0)
问题的正确样本是:
var highScore = 0;
labelHighScore.Text = highScore.ToString();
highScore = 42;
以这种方式编写它清楚地表明,首先显示值而不是更改它实际上不会显示更新的值。
修复:在显示之前设置值,可能labelHighScore.Text = highScore.ToString();
应该只移动到函数的末尾。
请注意,代码中可能存在其他问题,基于奇怪的方式HighScore
返回结果以及代码如何完全忽略函数的结果。