You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

传递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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:35:29