nullreferenceexception : object reference not set to an instance of an object
本问题已经有最佳答案,请猛点这里访问。
我有两个班级的球员和支持者。类播放器的一个字段是类支持程序的对象列表。当我试图将一个新对象添加到某个玩家的支持者列表中时,我得到了nullreferenceexception,我认为这是因为我从未初始化支持者列表,但我不知道在哪里以及如何初始化。下面是代码和类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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 2 3 4 5 |