我正在尝试为Unity编写一些C#代码,这些代码将从文本文件中读取,将每一行存储在字符串数组中,然后将其转换为2D char数组。
错误发生在:
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'
此错误意味着什么以及如何修复代码?
答案 0 :(得分: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];
}
}
答案 1 :(得分:0)
错误显示maze[i,j]
将string
,但line[i].Split(',');
会返回string[]
。
答案 2 :(得分:0)
迷宫的更好的数据结构在你的情况下是一个数组的数组,而不是2d数组。因此,您可以直接分配拆分操作的结果,而无需额外的副本:
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];