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

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

arrays - C# - Making classes in a for loop

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...