简体   繁体   English

C#对象引用未设置为对象的实例。

[英]C# Object reference not set to an instance of an object.

I have the following piece of code that is suppose to extract some info from a file. 我有以下一段代码,假设从文件中提取一些信息。

private string[][] users;
private string userID;

public void getInfo()
{

    string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");

    for (int i = 0; i < lines.Count(); i++ )
    {
        string[] values = lines[i].Split(',');
        for (int b = 0; b < 5; b++ )
        {

            users[i][b] = values[b];

        }


    }
}

the line users[i][b] = values[b]; users[i][b] = values[b];users[i][b] = values[b]; returns the error : " Object reference not set to an instance of an object. " but I am not sure why. 返回错误:“对象引用未设置为对象的实例。”但我不确定原因。 the code is suppose to read each line and split the line by , and create 2 dimensional array from the info. 代码是假设读取每一行并拆分行,并从信息创建二维数组。

我认为你需要为数组分配空间

string[,] users = new string[M,N];

Unless there's code you've not shown us, you never actually created the array. 除非您没有向我们展示代码,否则您从未真正创建过该阵列。 Therefore, users will be null , so attempt to dereference it doesn't make sense. 因此, users将为null ,因此尝试取消引用它是没有意义的。 Hence, the exception. 因此,例外。

You need to allocate users : 您需要分配users

string[][] users = new string[n][];
for(int i = 0; i < n; i++)
{
    users[i] = new string[m];
}

n and m can be variables. nm可以是变量。

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

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