System.NullReferenceException 基于列表<int>

System.NullReferenceException based on List<int>

我正在尝试遍历行并获取它们的索引(来自 SQL 的主键)。我在 "this.SelectRowIndexes.Add(ResourceKey)" 上遇到了 NRE 我不知道为什么这很重要,我该如何解决这个问题?

代码:

    private void GetIndexes()
    {
        List<int> SelectRowIndexes = new List<int>();
        for (int i = 0; i < gridViewRecords.Rows.Count; i++)
        {
            DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
            DataRow selectedRow = drv.Row;
            ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
            this.SelectRowIndexes.Add(ResourceKey);

        }
    }

我的 class 中也有它(这是大量的故障排除,所以我的代码看起来很糟糕)

    public List<int> SelectRowIndexes { get; set; }

我之前有过这个。有几个答案引用了这段代码。我更改了我的,因为 if-else 实际上用于其他用途,现在已被删除

if (this.SelectRowIndexes == null)
{
    this.SelectRowIndexes.Add(ResourceKey);
}
else
{
    this.SelectRowIndexes.Add(ResourceKey);
}

你实例化了一个局部变量

List<int> SelectRowIndexes = new List<int>();

然后你要添加到你的 class property/field this.SelectedRowIndexes 中,你很可能不会在任何地方分配它并且它是空的并且你得到 NRE。

this.SelectRowIndexes.Add(ResourceKey);

改成这样

private void GetIndexes()
{
    this.SelectRowIndexes = new List<int>();
    for (int i = 0; i < gridViewRecords.Rows.Count; i++)
    {
        DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
        DataRow selectedRow = drv.Row;
        ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
        this.SelectRowIndexes.Add(ResourceKey);
    }
}

如果 this.SelectRowIndexes 为空,您实际上想做什么?目前你只是无条件地调用 Add ,因为你的 if 语句的两个分支做同样的事情。

请注意,如果您为其分配了一个新值,它肯定 不会 为 null - 但在这一行中,您声明了一个名为SelectRowIndexes:

List<int> SelectRowIndexes = new List<int>();

...然后您就完全忽略了。也许您打算改为设置 property/field 的值?

SelectRowIndexes = new List<int>();

进行该更改后,您应该避免异常 - 但您仍将拥有基本损坏的代码。您几乎肯定应该摆脱 if 检查……它现在对您没有任何好处。

但是,我建议您可能 应该 resourceKey 声明一个单独的局部变量 - 事实上您正在循环中更新实例变量有点奇怪......事实上你根本没有使用你的循环索引......你在循环的每次迭代中做同样的事情,使用当前行而不是行 i .是故意的吗?

从根本上说,您可能想重新开始这段代码...看起来您可能只想使用 LINQ:

private void GetIndexes()
{
    SelectRowIndexes = gridViewRecords.Rows
        .Cast<DataRowView>()
        .Select(drv => (int) drv.Row["ResourceAndInstallKey"])
        .ToList();
}

如果 SelectRowIndexes 为 null,则您无法向列表中添加任何内容。您首先需要使用

初始化一个空列表
this.SelectRowIndexes = new List<int>();

this 关键字允许您访问 class 范围内名为 SelectRowIndexes 的成员。该成员可能未初始化。去掉List<int>类型声明就完美了

private List<int> SelectRowIndexes;
private void GetIndexes()
{
    SelectRowIndexes = new List<int>();
    for (int i = 0; i < gridViewRecords.Rows.Count; i++)
    {
        DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
        DataRow selectedRow = drv.Row;
        ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
        if (this.SelectRowIndexes == null)
        {
            this.SelectRowIndexes.Add(ResourceKey);
        }
        else
        {
            this.SelectRowIndexes.Add(ResourceKey);
        }
    }
}