传递List<ClassType>作为类参数时遇空引用异常问题排查
空引用异常排查与解决
问题原因
你遇到的NullReferenceException是因为Region类中的cities列表仅被声明,未初始化实例。在构造函数中直接调用cities.Add(com)时,cities还是null,无法执行添加操作。
修复方案
方案1:在字段声明时初始化列表
直接在cities字段定义时创建List实例,最直观:
public class Region { private string _region; private List<Commune> cities = new List<Commune>(); // 提前初始化列表 private string prefect; private string chief; public Region(string _r, List<Commune> c, string p, string C){ _region = _r; foreach (Commune com in c) { if(_r == com.Region){ cities.Add(com); } } prefect = p; chief = C; } // 其他代码... }
方案2:在构造函数开头初始化列表
如果需要延迟初始化,也可以在构造函数执行遍历前创建List实例:
public Region(string _r, List<Commune> c, string p, string C){ _region = _r; cities = new List<Commune>(); // 先初始化再使用 foreach (Commune com in c) { if(_r == com.Region){ cities.Add(com); } } prefect = p; chief = C; }
额外优化建议
可以用LINQ简化遍历筛选逻辑,替代手动foreach,代码更简洁易读:
public Region(string _r, List<Commune> c, string p, string C){ _region = _r; // 用LINQ直接筛选并生成新列表 cities = c.Where(com => com.Region == _r).ToList(); prefect = p; chief = C; }
注意事项
请确认Commune类中存在可访问的Region属性,否则构造函数中的com.Region会编译错误。比如Commune类需要类似这样的定义:
public class Commune { public string Name { get; } public int Department { get; } public string Region { get; } // 必须有这个公开属性 public string Mayor { get; } public int Population { get; } public Commune(string name, int department, string region, string mayor, int population) { Name = name; Department = department; Region = region; Mayor = mayor; Population = population; } }
内容的提问来源于stack exchange,提问作者Jeromeo
相关产品推荐
相关产品推荐

