2013-08-23 282 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]; 
相關問題