所以我一直使用C#創建一個測驗顯示(只是爲了好玩和學習) 在我的高分電網從playerdetails類的信息對同一個玩家顯示5次而不是一次。見代碼:寫入一個文本文件在C#中,但是當它在網格中的相同信息的重複是
public frmHighscore()
{
InitializeComponent();
//Only save the test scores once
if (!File.Exists("highscores.txt"))
{
SaveScores();
}
LoadScores();
//Sort the grid based on the value of Column 1 which will be the score value
dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Descending);
}
private void SaveScores()
{
//Open filestram and streamwriter needed to save details to a text file
FileStream fileStream = new FileStream("highscores.txt", FileMode.Append, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
try
{
//loop over each player
{
//Write details of the player to the textfile in format playerName~Score
foreach (Player player in PlayerList)
{
streamWriter.WriteLine(player.playerName + "~" + player.playerScore);
}
}
}
catch (Exception)
{
MessageBox.Show("Error loading the scores", "Please try again");
}
finally
{
//close streamwriter and filestream
streamWriter.Close();
fileStream.Close();
}
}
private void LoadScores()
{
//Check if the file exists
if (File.Exists("highscores.txt"))
{
//Read in all the details of the text file
var playerScores = File.ReadAllLines("highscores.txt");
//check if players exist in the text file
if (playerScores.Length > 0)
{
//Loop over each player details
foreach (var playerScore in playerScores)
{
//Add the player name and score to the datagrid
var splitDetails = playerScore.Split('~');
dataGridView1.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[1]));
}
}
else
{
//Hide the grid and show the No Scores label
HideGrid();
}
}
我Player類看起來是這樣的: 命名空間CWQuiz
{
public class Player
{
public string Username;
public int Score;
public int quizNumber;
public string playerName { get; set; }
public int playerScore { get; set; }
public static List<Player> player = new List<Player>();
public Player(string name)
{
Username = name;
Score = 0;
}
}
}
foreach(PlayerDetails中的var播放器) streamWriter.WriteLine(player.playerName +「〜」+ player.playerScore); } –
'PlayerDetails.playerName'是什麼類型? –
這是一個字符串類型 –