[英]How to give variable names to variables? c#
Well, my problems is the following, I have a class named player, and I want to generate n objects whose name are "myPlayerN" where N is the number of the object, so I can use them later for diferent purposes. 好吧,我的问题如下:我有一个名为player的类,并且我想生成n个对象,它们的名称为“ myPlayerN”,其中N是对象的编号,因此以后可以将它们用于不同的目的。 This better explained would be something like:
更好的解释是:
int numplayers=n;
for(i=0;i<numplayers;i++)
{
player myPlayer+numplayers = new player();
}
You are looking for an array
. 您正在寻找一个
array
。
var players = new player[numplayers];
for(int i = 0; i < players.Length; i++)
players[i] = new player();
Shorter way: 较短的方法:
var players = Enumerable.Range(0, numplayers)
.Select(x => new player()).ToArray();
After that you can access your players using an index (eg players[2]
).Remember that array indices are zero-based , so the first element of your array is players[0]
not players[1]
.Refer to the msdn documentation for detailed information about arrays. 之后,您可以使用索引访问玩家(例如
players[2]
)。请记住数组索引是从零开始的 ,因此数组的第一个元素是players[0]
而不是players[1]
参阅msdn文档有关数组的详细信息。
Further reading 进一步阅读
You need either an array or a list. 您需要一个数组或一个列表。 Since you probably don't know, in advance, how many you will need, I suggest a list:
由于您可能事先不知道需要多少,因此建议您列出:
List<player> players = new List<player>();
var p = new player();
players.Add(p);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.