'Object reference not set' 错误,但列表在 C# .Net 中有 27 个引用

'Object reference not set' error, but list has 27 references in C# .Net

我正在使用 Visual Studio 2019,但在尝试填充列表时出现此错误。我的同事试图帮助我并认为收到以下错误很奇怪,因为我的列表有 27 个对对象的引用,所以它的一部分被识别但部分不是:

An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object.

以下是部分模型:

public class BogusModel
{
    public List<County> Counties { get; set; }
    public SelectList CountySelectList { get; set; }
}

这里是 class 在模型中的位置:

public class County
{
    public string CountyName { get; set; }
    public double CountyRate { get; set; }

    public County(string CountyName, double CountyRate)
    {
        this.CountyName = CountyName;
        this.CountyRate = CountyRate;
    }

    public County()
    {
    }
}

这是我尝试在模型中填充列表的方法的开头:

public void createAndPopulateCounties()
{
    Counties.Add(new County(CountyName = "Allegany", CountyRate = 0.0305));
}

以及调用该方法的控制器(我注释掉了 select 列表,因为它也不起作用):

[HttpGet]
public IActionResult Index()
{
    BogusModel model = new BogusViewModel();

    // Call the method to create and populate the list of counties
    model.createAndPopulateCounties();

    // model.CountySelectList = new SelectList(model.Counties, "CountyName", "CountyName");

    return View("Index", model);
}

我和我的同事尝试更改县 class 中的代码 this.CountyName = CountyName; 几种不同的方式,我以前在我的函数中有这样的代码

List<County> Counties = new List<County>();

但这是个问题,因为它没有填充原始列表,而是创建了第二个列表(我的同事注意到了这一点)。我无法从其他堆栈溢出帖子中弄清楚这一点,其他帖子中的 none 提到了对该对象的引用。我试图上传参考图片,但 Whosebug 说这是被禁止的。但它确实引用了我尝试添加的 County 对象,但随后出现运行时错误。

由于您没有将任何参数传递给模型的构造函数,因此您可以在初始化模型时尝试初始化列表,例如:

WithholdingViewModel model = new WithholdingViewModel{
    Counties = new List<County>()
};

或者,如果您已经有了 County 个对象的列表,可以这样做:

List<County> myCountyListFromEarlier = someMethodToBuildTheList();

WithholdingViewModel model = new WithholdingViewModel{
    Counties = myCountyListFromEarlier
};