C# - 在for循环中创建类

时间:2016-02-17 11:08:01

标签: c# arrays class for-loop

我有这堂课:

class player
{
  public string name;
  public int rating;

{

这些课程的数量取决于用户指定的金额numberOfPlayers。所以我的第一反应是创建一个for循环来做到这一点。即:

for (int i = 0; i< numberOfPlayers; i++)
{
    //create class here
}

但是,我需要能够在以后使用他们的个人数据时单独访问这些类 - 几乎就像他们已被放入数组中一样。我将如何制作一些可以单独访问的课程?

3 个答案:

答案 0 :(得分:2)

您使用List<T>变量,其中T是您的班级

List<Player> players = new List<Player>();
for (int i = 0; i< numberOfPlayers; i++)
{
    Player p = new Player();
    p.Name = GetName();
    p.rating = GetRating();
    players.Add(p);
}

当然,GetName和GetRating应该由您的代码替换,这些代码会检索这些信息并将它们添加到单个播放器中。

List<T>中获取数据与从数组中读取数据没有什么不同

if(players.Count > 0)
{
    Player pAtIndex0 = players[0];
    ....
}

您可以在MSDN page on List class

阅读更多信息

答案 1 :(得分:0)

你有正确的想法。制作一个可以反复使用的玩家类,一个创建这些玩家的循环,现在我们需要将它们存储在某个地方。如果你得到多个答案,这可能会分歧意见,但我喜欢这类词的字典,因为你可以通过唯一键来访问值。

// Your player class. I've added 'id' so we can identify them by this later.
class Player
{
    public int id;
    public string name;
    public int rating;
}

// The dictionary. They work like this dictionary<key, value> where key is a unique identifier used to access the stored value. 
// Useful since you wanted array type accessibility
// So in our case int represents the player ID, the value is the player themselves
Dictionary<int, Player> players = new Dictionary<int, Player>();

// Create your players
for (int i = 0; i < numberOfPlayers; i++)
{
    Player p = new Player()
    {
        id = i + 1,
        name = $"Player{i}",
        rating = 5
    };

    // Add them to dictionary
    players.Add(p.id, p);
}

// Now you can access them by the ID:
if (players.ContainsKey(1))
{
    Console.WriteLine(players[1].name);
}

字典键可以是您喜欢的任何内容,只要它是唯一的。如果您愿意,可以按名称识别它们。

答案 2 :(得分:0)

List<Player> players = new List<Player>();
for (int i = 0; i< numberOfPlayers; i++)
{
    Player p = new Player();
    p.Name = "";
    p.rating = "";
    players.Add(p);
}

单独访问它可以使用...

foreach(Player p in players )
    {

    }