数组中的所有对象都等于c#中最后添加的对象

本文关键字:对象 最后 添加 数组 | 更新日期: 2023-09-27 18:02:47

我创建了一个名为"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, "

数组中的所有对象都等于c#中最后添加的对象

Player类的private static string player_name;中移除static。使用该关键字,您是特别是告诉它使Player的所有实例具有相同的name

没有它,name将是一个实例字段,并且可以为Player的每个实例单独设置和检索。