【问题标题】:Null reference on an apparent not null object对明显非空对象的空引用
【发布时间】:2011-04-10 13:51:33
【问题描述】:

首先是我的代码:

我已经评论了问题行

protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader reader = new StreamReader(Request.PhysicalApplicationPath +  "/directory.txt");
        int i = 0;
        int c = 0;
        int d = 0;
        List<string> alst = new List<string>();
        List<string> nlst = new List<string>();
        TableRow[] row = new TableRow[100];
        TableCell[] cella = new TableCell[100];
        TableCell[] cellb = new TableCell[100];
        while (reader.Peek() > 0)
        {
            alst.Add(reader.ReadLine());
            nlst.Add(reader.ReadLine());
            d++;
        }
        foreach (string line in nlst)
        {
            if (i < d + 1)
            {
                cella[i].Text = nlst[i]; //this line
                cellb[i].Text = alst[i]; //and this line always return a null return a null reference when ran
                i++;
            }
        }
        do
        {
            row[c].Cells.Add(cella[c]);
            row[c].Cells.Add(cellb[c]);
            c++;
        } while (c != cella.Count());
        foreach (TableRow item in row)
        {
            Table1.Rows.Add(item);
        }
    }

我检查过,所有涉及的变量都不为空。我试过清洗溶液。我也尝试将静态值放入 for i(如 0),仍然没有。

我已经盯着这个东西看了至少 2 个小时,改变了循环、ifs 和其他东西,但仍然无法弄清楚。

提前致谢, 亚当

【问题讨论】:

  • 附带说明,您最好使用using 块来正确处理StreamReader,否则存在文件锁定甚至内存泄漏的风险。

标签: c# asp.net nullreferenceexception


【解决方案1】:
TableCell[] cella = new TableCell[100];
TableCell[] cellb = new TableCell[100];

这会创建一个数组,但不会初始化它的值。所以

cella[i].Text = nlst[i];
cellb[i].Text = alst[i];

失败,因为cella[i] 始终是null 并且.Text 不存在(同样适用于cellb[i])。

你必须先初始化你的数组或者在你的循环中生成一个新的 TableCell 对象

cella[i] = new TableCell { Text = nlst[i] };
cellb[i] = new TableCell { Text = alst[i] };

此外:

  • 考虑使用 LINQ 来处理列表操作和
  • 尝试将变量重命名为更有意义的变量。 cellb[i] = new TableCell { Text = alst[i] }; 对我来说似乎是个错误 - N 转到单元格 AA 转到单元格 B
  • 在处理流(和其他IDisposable 对象)时使用using 语句。这样可以确保正确处理流 - 即使发生错误。
using(var reader = new StreamReader(Request.PhysicalApplicationPath + "/directory.txt");) { // 你的代码她... }

【讨论】:

    【解决方案2】:

    当您声明 TableCell[] cella = new TableCell[100]; 时,您正在创建一个包含 100 个对 TableCell 的引用的数组,所有这些引用都是 null。如果你尝试执行cella[i].Text = nlst[i];cella[i] 就是null,所以你尝试分配null.Text 时会出现异常。

    听起来您需要一个循环来填充cellacellb 的所有元素的值。

    【讨论】:

    • 有时我觉得自己很愚蠢……我应该想到这一点。谢谢你的帮助。
    【解决方案3】:

    您永远不会实例化该数组中的TableCell 对象;您只是在实例化数组本身。您需要先为每个条目创建new TableCell() 对象,然后才能使用它们的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 2018-06-10
      相关资源
      最近更新 更多