首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >空引用异常:未设置为对象实例的对象引用

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

Stack Overflow用户
提问于 2014-12-11 18:20:34
回答 1查看 695关注 0票数 1

我有两个班球员和支持者。类Player的字段之一是类支持者的对象列表。当我试图为某个球员的支持者列表添加一个新的对象时,我得到了NullReferenceException,我认为这是因为我从来没有初始化过支持者列表,但是我不知道在哪里以及如何初始化。下面是代码和类:

代码语言:javascript
复制
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 });
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-11 18:23:33

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

代码语言:javascript
复制
public class Player {
   public Player() {
     supporters = new List<Supporter>();  
   }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27429774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档