-1

我正在尝试为 Unity 编写一些 C# 代码,这些代码将从文本文件中读取,将每一行存储在字符串数组中,然后将其转换为 2D 字符数组。

错误发生在:

void ReadFile()
{
    StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
    int length = read.ReadLine().Length;
    maze = new string[length, length];
    line = new string[length];

    while(!read.EndOfStream)
    {
        for (int i = 0; i <= length; i++)
        {
            line[i] = read.ReadLine();
        }
        for( int i = 0; i <= length; i++)
        {
            for( int j = 0; j <= length; j++)
            {
                maze[i,j] = line[i].Split(','); // <---This line is the issue.
            }       
        }
    }
}

我得到的确切错误是:

Cannot Implicitly convert type 'string[]' to 'string'

这个错误是什么意思,我该如何修复代码?

4

3 回答 3

2

我有一种感觉,你打算这样做:

    for( int i = 0; i <= length; i++)
    {
        var parts = line[i].Split(',');
        for( int j = 0; j <= length; j++)
        {
            maze[i,j] = parts[j];
        }       
    }
于 2013-08-23T00:48:21.983 回答
0

正如错误所说,maze[i,j]将采取 astringline[i].Split(',');会返回 a string[]

于 2013-08-23T00:47:54.373 回答
0

迷宫的更好数据结构在您的情况下是数组数组,而不是二维数组。因此,您可以直接分配拆分操作的结果,而无需额外的副本:

StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
string firstLine = read.ReadLine();
int length = firstLine.Length;
string[][] maze = new string[length][];

maze[0] = firstLine.Split(',');

while(!read.EndOfStream)
{
    for (int i = 1; i < length; i++)
    {
        maze[i] = read.ReadLine().Split(',');
    }
}

然后,您可以访问类似于 2d 数组的迷宫:

var aMazeChar = maze[i][j];
于 2013-08-23T01:13:30.360 回答