2013-08-23 283 views
-1

我想写一些Unity代码的C#代码,它将从文本文件读取,将每行存储在字符串数组中,然后将其转换为2D字符数组。发生C#错误:不能将字符串[]'转换为'字符串'

错误的:

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

这一行:INT长度= read.ReadLine ()。长度;将推进一行的流,然后在for循环中,你从第2行开始读取。 – thalm

+0

是的,这很好,文件的长度,宽度和高度都是相同的。 – user2709291

+0

但是你需要文本的第一行还是不行?因为在你的代码中,第一行会被忽略。 – thalm

回答

0

如错误说maze[i,j]将采取stringline[i].Split(',');将返回string[]

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]; 
     }  
    } 
+0

谢谢,真的有帮助。我能够正常工作。 – user2709291

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(','); 
    } 
} 

然后,您可以访问类似二维数组的迷宫:

var aMazeChar = maze[i][j]; 
相关问题