C# - Making classes in a for loop

2019-09-22 01:52发布

问题:

I have this class:

class player
{
  public string name;
  public int rating;

{

The number of these classes made is dependant on a user specified amount numberOfPlayers. So my first reaction was to create a for loop to do this. i.e:

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

However, I need to be able to access these classes individually when later using their individual data - almost like they've been put into an array. How would I go about making a number of classes of which can be accessed individually?

回答1:

You use a List<T> variable where T is your class

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);
}

Of course GetName and GetRating should be substituded by your code that retrieves these informations and add them to the single player.

Getting data out of a List<T> is in no way very different from reading from an array

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

You can read more info at MSDN page on List class



回答2:

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

to access it individually you can use...

foreach(Player p in players )
    {

    }


回答3:

You've got the right idea. Make a player class that can be re-used over and over, a loop in which to create these players and now we need to store them somewhere. This will probably divide opinion if you get more than one answer but I like dictionaries for this kind of thing as you can access values by unique keys.

// 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);
}

The dictionary key can be anything you like so long as it's unique. You could identify them by name if you like.