2015-06-26 39 views
-5

我應該如何在我的代碼中處理這個錯誤?我試圖改變清單列出,但是會有這個說法是錯誤:不能隱式地將'string'轉換爲'string []'

string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff); 

下面顯示的是,我做的部分代碼..

List<string[]> dataCollection = new List<string[]>(); 
List<string> timeCollection = new List<string>(); 
    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
    { 
     string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff"); 

     if (x == unit && count == 3) 
     { 
      dataCollection.Add(ReceivedData); 
      timeCollection.Add(time); 

      for (int i = 0; i < dataCollection.Count(); i++) //write out all the data lines 
      { 
       string[] dataArray = dataCollection[i]; 
       string dataOutput = ""; 

       for (int j = 0; j < dataArray.Length; j++) 
       { 
        dataOutput += dataArray[j] +" "; //Link all data to write out 
       } 
      for (int k = 4; k > timeCollection.Count(); k--) 
      { 
       string[] timeArray = timeCollection[k]; //error for timeCollection[k] 
       string timeOutput = ""; 

       for (int t = 0; t < timeArray.Length; t++) 
       { 
        timeOutput += timeArray[t]; 
       } 
      } 
+4

正如錯誤消息說:'timeCollection [K]'返回一個字符串。另一方面,'dataCollection [k]'返回一個String []。 – user2864740

+0

@ user2864740 right ...所以我應該修改它,以便timeCollection [k]也會返回一個字符串[]。 – Athena

+0

當且僅當這是所需的。然後String []對象必須放入這裏。他們來自哪裏?爲什麼?他們如何使用? (他們甚至認爲是字符串數組?) – user2864740

回答

3

對象timeCollection是名單字符串,因此當您訪問列表元素(timeCollection[k])時,您將返回string,但您正試圖將其分配給數組。

string[] timeArray = timeCollection[k]; 

試試這個:

string timeValue = timeCollection[k] 

或者你可能需要修改timeCollection所以它是字符串數組列表,但似乎並沒有這樣的情況,因爲變量time是隻是一個字符串而不是數組。

它還在我看來,你的兩個for循環可以由這些線所取代:

string dataOutput = String.Join(" ", dataCollection.SelectMany(x => x)); 
string timeOutput = String.Join("", timeCollection.Take(4).Reverse()); 
相關問題