简体   繁体   English

我该如何处理这个NullReferenceException?

[英]How do I deal with this NullReferenceException?

public partial class Form1 : Form
{
    string[] id;

private void button_Click(object sender, EventArgs e)
{
    char[] delimiters = { ',', '\r', '\n' };
    string[] content = File.ReadAllText(CSV_File).Split(delimiters);

    int x = content.GetUpperBounds(0)
    int z = 0;
    int i - 0;

    for (i = 0; i <= x / 3; i++)
        {
            z = (i * 3);
            id[i] = content[z]; // this line gives the error
        }

}
}

I want to get every 3rd value from array content, and put it into array id. 我想从数组内容中获取每个第3个值,并将其放入数组ID中。 This gives a 'NullReferenceException was unhandled' error and suggests I use 'new', but it is not a type or namespace. 这给出了'NullReferenceException未处理'错误,并建议我使用'new',但它不是类型或命名空间。 What should I do here? 我该怎么办?

They are both string arrays, and the error occurs on the first run so I do not think it is related to exceeding the bounds. 它们都是字符串数组,并且在第一次运行时发生错误,因此我认为它与超出边界无关。

您需要在for循环之前初始化id数组:

id = new string[x/3];

This line of code: 这行代码:

string[] id;

is actually creating a null reference. 实际上是创建一个null引用。

When you declare an array, you have to explicitly create it, specifying the size. 声明数组时,必须显式创建它,指定大小。

In your example, you have two alternatives 在您的示例中,您有两种选择

  1. Determine how big the array will be beforehand, and create the array length 确定预先确定的数组大小,并创建数组长度
  2. Actually populate a container that manages its own size. 实际上填充管理自己大小的容器。

The first option: 第一种选择:

int x = content.GetUpperBounds(0)
int z = 0;
int i - 0;

id = new string[x/3];
for (i = 0; i <= x / 3; i++)
    {
        z = (i * 3);
        id[i] = content[x];
    }

The second option: 第二种选择:

int x = content.GetUpperBounds(0)
int z = 0;
int i - 0;

List<string> list = new List<string>();
for (i = 0; i <= x / 3; i++)
    {
        z = (i * 3);
        list.Add(content[z]);
    }

id = list.ToArray();

The first option would perform better, as you are only allocating one object. 第一个选项会更好,因为您只分配一个对象。

Admittedly, I tend to disregard performance and use the second option, because it takes less brainpower to code. 不可否认,我倾向于忽视性能并使用第二种选择,因为代码需要较少的智力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM