C# - 在for循环中创建类 [英] C# - Making classes in a for loop
问题描述
class player
{
公共字符串名称;
public int rating;
这些类的数量取决于指定的用户金额 numberOfPlayers
。所以我的第一反应是创建一个for循环来做到这一点。即:
$ p $ for(int i = 0; i< numberOfPlayers; i ++)
{
//在这里创建类
}
但是,我需要能够单独访问这些类后来使用他们的个人数据 - 就像他们已经被放入一个数组。我将如何去做一些类可以单独访问?
您使用列表< 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 class上的MSDN页面 I have this class: The number of these classes made is dependant on a user specified amount 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? You use a 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 You can read more info at MSDN page on List class 这篇关于C# - 在for循环中创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
从
{
Player pAtIndex0 =玩家[0];
....
$ / code $ / pre
class player
{
public string name;
public int rating;
{
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
}
List<T>
variable where T is your classList<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);
}
List<T>
is in no way very different from reading from an arrayif(players.Count > 0)
{
Player pAtIndex0 = players[0];
....
}