空引用异常:对象引用未设置为对象的实例

本文关键字:对象 实例 设置 引用 异常 对象引用 | 更新日期: 2023-09-27 18:34:03

我有两个类玩家和支持者。类玩家的字段之一是类支持者的对象列表。当我尝试将新对象添加到某个玩家的支持者列表中时,我得到了 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 });
    }
}

空引用异常:对象引用未设置为对象的实例

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

public class Player {
   public Player() {
     supporters = new List<Supporter>();  
   }
}