nullreferenceexception:对象引用未设置为对象的实例

时间:2014-12-11 18:20:34

标签: c# initialization nullreferenceexception

我有两个类播放器和支持者。 Player类的一个字段是类Supporter的对象列表。当我尝试将新对象添加到某个玩家的支持者列表时,我得到NullReferenceException,我认为这是因为我从不初始化支持者列表,但我不知道在哪里以及如何初始化。这是代码和类:

public class Player
{
    public string name { get; set; }
    public int numMention { get; set; }

    public double s { get; set; }
    public double salience { get; set; }
    public double supportForPlayer1 { get; set; }
    public double supportForPlayer2 { get; set; }
    public double supportDiff { get; set; }
    public double position { get; set; }
    public List<Supporter> supporters { get; set; }
}

public class Supporter
{
    public string name { get; set; }
    public double GFP { get; set; }
    public double supportAmount {  get;  set; }
}

foreach (var val in playersList)
{
    sql = "SELECT Actor2CountryCode,SUM(GoldsteinScale) AS SupportForPlayer2 FROM [gdelt-bq:full.events] WHERE Year>=" + predictionDate + " AND (Actor1Code='" + val.name + "' AND (Actor2Code!='" +    val.name + "' AND Actor2Code!=' ')) GROUP BY Actor2CountryCode";

    response = new WebClient().DownloadString(url + "?q=" + Uri.EscapeUriString(sql));
    value = JsonValue.Parse(response);
    result = value as JsonObject;

    for (int i = 0; i < result["modelData"]["rows"].Count; i++)
    {
        row = result["modelData"]["rows"][i];

        if (row["f"][0]["v"] != null && row["f"][1]["v"] != null)
            val.supporters.Add(new Supporter { name = (string)row["f"][0]["v"], supportAmount = (double)row["f"][1]["v"], GFP = 0 });
        else
            val.supporters.Add(new Supporter { name = "NULL", supportAmount = 0, GFP = 0 });
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在Player中添加构造函数,例如:

public class Player {
   public Player() {
     supporters = new List<Supporter>();  
   }
}
相关问题