C# 如何允许用户输入实例变量并创建多个对象?

C# How do I allow a user to enter instance variables and create multiple objects?

我正在尝试创建一个程序,在用户输入后 "how many player's details would you like to enter?" 要求用户输入这些玩家的每个属性。

本质上,我试图让用户实例化 class 的多个对象。

这是我在 FootBallPlayer 中输入的 class

class FootballPlayer
{
  private string fullName;
  private int yearBorn;
  private double goalsPerGame;

  // constructor
  public FootballPlayer (string name, int year, double goals)

  {
     fullName = name;
     yearBorn = year;
     goalsPerGame = goals;
  }

  // read-only properties
  public string Name;
  {
     get
       { 
          return fullName;

   public string YearBorn;
  {
     get
       { 
          return yearBorn;
       }
  }

  public string Goals;
  {
     get
       { 
          return goalsPerGame;
       }
  }

在我的第二个 class FootballPlayerApp 中,我试图让用户首先输入球员的数量,然后输入所有这些用户的详细信息。

我创建了以下方法 GetInput() //它允许用户输入玩家数量并 returns 它 GetName() //允许用户输入玩家姓名 GetYear() //允许用户输入出生年份 GetGoals() // 允许用户输入进球数。

我明白我可以在main方法中创建单个对象如下

FootballPlayer player1 = new
FootballPlayer ("Lionel Messi", 1988, 2.3);

我不明白的是

例如,如果用户输入了 2 个玩家 玩家 1("Lionel Messi",1998 年,2.3) 播放器 2("Ronaldo",1985 年,1.4)

如何让结果显示为

 Player Name    Year Born     Average Goals Scored

 Lionel Messi        1998                      2.3
 Ronaldo             1985                      1.4

how do I have the name of the object (e.g player1 in the example above) be different for each player

你不知道。考虑 collection of objects,而不是单个变量。基本上,每当您发现自己尝试创建 object1object2object3 等时,您 可能 想要使用数组或collection 某种形式。

这可以是任意数量的 collection 类型之一,甚至是一个简单的数组。在这种情况下使用的常见类型是 List<T>,对于您的类型来说是 List<FootballPlayer>.

在结构上它可能看起来像这样:

var players = new List<FootballPlayer>();
var numberOfPlayers = GetInput();
for (var i = 0; i < numberOfPlayers; i++)
{
    // prompt the user to enter the next player

    var player = new FootballPlayer();
    player.Name = GetName();
    player.Goals = GetGoals();
    // etc.  Basically build up a FootballPlayer object from user input

    players.Add(player);
}

系统会针对每个玩家提示用户,您可以在循环中使用 i 变量来提供有用的消息。例如,"Enter the details for player 2:" 或类似的东西。

循环完成后,players 变量中的 collection 为 FootballPlayer objects。