调用期望对象数组的方法

Ian*_*ter 2 c# oop

我正在学习C#并编写了一个控制台程序来保存一个高分数到一个文件.虽然该程序有效,但我如何使它工作让我感到不安,感觉更像是一个黑客而不是一个解决方案所以我正在寻找关于如何编写它的指导.

我目前在Main方法中做的是:

  1. 声明一个高分对象数组
  2. 初始化它们
  3. 为数组分配一些值.

我很高兴我到目前为止做了什么,这是让我感到不安的以下两个步骤

  1. 然后我宣布另一个HighScore对象
  2. 我使用此对象将高分数组传递给SaveHighScores方法.

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace HighScore
{
    class HighScore
    {
        public string Name { get; set; }

        public int Score { get; set; }

        public void SaveHighScores(HighScore[] highScores)
        {
            string allHighScoresText = "";

            foreach (HighScore score in highScores)
            { 
                allHighScoresText += $"{score.Name},{score.Score}" + Environment.NewLine;
            }

            File.WriteAllText("C:/Temp/highscores.csv", allHighScoresText);
        }

        static void Main(string[] args)
        {
            HighScore[] highScore = new HighScore[2];

            for (int i = 0; i < highScore.Length; i++)
            {
                highScore[i] = new HighScore();
            }

            highScore[0].Name = "A";
            highScore[0].Score = 100;

            highScore[1].Name = "B";
            highScore[1].Score = 200;

            // are the following two lines correct or am I missing something?
            HighScore hs = new HighScore();

            hs.SaveHighScores(highScore);

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

adv*_*v12 6

使SaveHighScores静态,你不需要一个实例HighScore来调用它.(您可以直接调用它HighScore.SaveHighScores())