C#null引用错误

时间:2013-11-12 18:23:42

标签: c#

似乎无法在这里找到什么问题,我正在使用这种方法:

public void AddPlayerToTeam(Player player, Team team)
{
    Team t = new Team();
    if(team.PlayersList.Count>=20)
        return;
    if (!(team.PlayersList.Contains(player)))
        team.PlayersList.Add(player); 
}

以及后来的测试:

[TestMethod]
public void CheckTeamOfPlayer9()
{
    Assert.AreEqual(wcm.GetPlayerById(9).PlayerTeam.CountryName, "Japan");
}

我收到以下错误:Object reference not set to an instance of an object.带有空引用异常。 这是测试运行的方法:

public Player GetPlayerById(int playerId)
{
    var result = from b in Players
                 where b.PersonId.Equals(playerId)
                 select b;

    return result.FirstOrDefault(); 
}

任何人都有想法?

1 个答案:

答案 0 :(得分:1)

如果没有匹配,

return result.FirstOrDefault()将返回默认值。在Player的情况下,这是null。

检查wcm.GetPlayerById(9)的结果。据推测它是空的。