从文件读取时出现 NullReferenceException

发布于 2024-08-31 15:31:20 字数 895 浏览 16 评论 0原文

我需要读取一个如下结构的文件:

01000
00030
00500
03000
00020

并将其放入这样的数组中:

int[,] iMap = new int[iMapHeight, iMapWidth] {
{0, 1, 0, 0, 0},
{0, 0, 0, 3, 0},
{0, 0, 5, 0, 0},
{0, 3, 0, 0, 0},
{0, 0, 0, 2, 0},
};

希望您看到我在这里尝试做的事情。我很困惑如何做到这一点,所以我在这里询问,但我从中得到的代码收到此错误:

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

我对此很陌生,所以我不知道如何解决它...我几乎不知道代码:

protected void ReadMap(string mapPath)
{
    using (var reader = new StreamReader(mapPath))
    {
        for (int i = 0; i < iMapHeight; i++)
        {
            string line = reader.ReadLine();
            for (int j = 0; j < iMapWidth; j++)
            {
                iMap[i, j] = (int)(line[j] - '0');
            }
        }
    }
}

我收到错误的行是这样的:

iMap[i, j] = (int)(line[j] - '0');

任何人都可以提供解决方案吗?

I need to read a file structured like this:

01000
00030
00500
03000
00020

And put it in an array like this:

int[,] iMap = new int[iMapHeight, iMapWidth] {
{0, 1, 0, 0, 0},
{0, 0, 0, 3, 0},
{0, 0, 5, 0, 0},
{0, 3, 0, 0, 0},
{0, 0, 0, 2, 0},
};

Hopefully you see what I'm trying to do here. I was confused how to do this so I asked here on SO, but the code I got from it gets this error:

Object reference not set to an
instance of an object.

I'm pretty new to this so I have no idea how to fix it... I only barely know the code:

protected void ReadMap(string mapPath)
{
    using (var reader = new StreamReader(mapPath))
    {
        for (int i = 0; i < iMapHeight; i++)
        {
            string line = reader.ReadLine();
            for (int j = 0; j < iMapWidth; j++)
            {
                iMap[i, j] = (int)(line[j] - '0');
            }
        }
    }
}

The line I get the error on is this:

iMap[i, j] = (int)(line[j] - '0');

Can anyone provide a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽月 2024-09-07 15:31:20

在此行中,StreamReader.ReadLine可能返回 null:

string line = reader.ReadLine();

您应该检查这种情况并适当处理。

string line = reader.ReadLine();
if (line == null)
{
    // Handle the error.
}

另请确保您的输入至少包含 iMapHeight * iMapWidth 行。

您还应该确保您的数组已初始化。例如,将此行添加到方法的开头:

iMap = new int[iMapHeight, iMapWidth];

On this line, StreamReader.ReadLine can return null if the end of file is reached:

string line = reader.ReadLine();

You should check for this condition and handle it appropriately.

string line = reader.ReadLine();
if (line == null)
{
    // Handle the error.
}

Also make sure that your input has at least iMapHeight * iMapWidth lines.

You should also make sure that your array is initialized. For example, add this line to the start of your method:

iMap = new int[iMapHeight, iMapWidth];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文