好的,我试图制作一些东西,但它不适合我,我认为它会。 Bassicly我试图添加到自定义类数组中的列表,这是否有意义。 以下是一些可能更容易理解的代码:
public class pfft
{
public class Player
{
public string Name { get; set; }
public int br { get; set; }
}
public class team
{
public int totalbr { get; set; }
public List<Player> players { get; set; }
}
}
public pfft.team[] Teams;
public int tmcount = 4;
private void btn_team_Click(object sender, EventArgs e)
{
Teams = new pfft.team[tmcount]();
foreach(pfft.Player p in getallplayers())
{
Teams[0].players.Add(p);
}
}
这正是所有我正在做的,但是当试图将玩家添加到玩家列表时它会崩溃。你调用的对象是空的。 它试图添加的确实包含值,我在调试器中检查了它 我也尝试过调用
Teams[0].players = new List<pfft.Player>();
但是当我尝试它会给那个部分的Nullexception ...
答案 0 :(得分:1)
这里有两个问题:
创建数组不会创建其对象:
因此您需要遍历数组并创建这些对象:
for (int i = 0; i < tmcount; ++i)
Teams[i] = new pfft.team();
您未在public List<Player> players { get; set; }
之后初始化Teams = new pfft.team[tmcount]();
:
Teams = new pfft.team[tmcount]();
foreach(pfft.Player p in getallplayers())
{
Teams[0].players = new List<pfft.Player>();
Teams[0].players.Add(p);
}
为了不必在每个团队中初始化玩家,请使用稍微不同的属性:
public class Team
{
private List<Player> players = new List<Player>();
public int totalbr { get; set; }
public List<Player> Players
{
get { return players; }
set { players = value; }
}
}