我创建了一个名为“Player”的类,它存储每个玩家的数据。 该类执行它应该做的事情,但是当在List / Array中存储该类的多个实例时,数组或列表中的所有对象都等于最后存储的对象。
玩家类代码:
public class Player
{
private static string player_name;
public Player(string name)
{
player_name = name;
}
public string Name
{
get
{
return player_name;
}
}
}
用于创建和添加到列表的代码:
//simple string array for names;
string[] example_names = new string[] { "Mike", "Adam", "Jake" };
//creating new object and adding to list<Player>
List<Player> players = new List<Player>();
foreach (string name in example_names)
{
Player player = new Player(name);
players.Add(player);
}
//loop for returning the output
string output = "";
foreach (Player player in players)
{
output += player.Name + ", ";
}
Clipboard.SetText(output);
输出:“Jake,Jake,Jake,”
答案 0 :(得分:9)
从班级static
中的private static string player_name;
移除Player
。使用该关键字,您专门告诉它使Player
的所有实例具有相同的name
。
没有它,name
将是实例字段,可以为Player
的每个实例单独设置和检索。