Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
390 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...