2017-02-22 97 views
-2

我在運行時遇到了這個錯誤。 如果你能解釋這對我的編碼有很大的幫助。謝謝。我的代碼錯誤「System.IndexOutOfRangeException」

public int timePeriodInSeconds(String timeInFormat) 
    { 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeInFormat= " + timeInFormat); 
     String[] timeFactors = timeInFormat.Split(':'); 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[0]" + timeFactors[0]); 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[1]" + timeFactors[1]); 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[2]" + timeFactors[2]); 

     int hours = Convert.ToInt32(timeFactors[0]); 
     int minutes = Convert.ToInt32(timeFactors[1]); 
     int seconds = Convert.ToInt32(timeFactors[2]); 

     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds hours" + hours); 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds minutes" + minutes); 
     System.Diagnostics.Debug.WriteLine("timePeriodInSeconds seconds" + seconds); 

     return (hours * 60 * 60 + minutes * 60 + seconds); 

    } 
+1

'timeFactors'只有1個位置,並且您試圖訪問第二個(超出邊界)。只是調試你的代碼 – Petaflop

+0

謝謝先生。我對這種語言很陌生。這個編碼部分是由我的朋友完成的。現在我想開發這個。所以這個錯誤發生了,你可以進一步解釋。 – SNP

+0

如果您不熟悉該語言,我建議您購買一些書並開始使用。在這個特殊情況下,這應該有助於你理解發生了什麼:http://csharp.net-tutorials.com/basics/arrays/ – Petaflop

回答

0

此異常意味着您嘗試使用無效索引按索引訪問集合項目。當索引低於集合的下限或大於或等於其包含的元素數量時,索引無效。

鑑於陣列聲明爲:

byte[] array = new byte[4]; 

可以訪問從0這個陣列3,在此範圍之外的值將導致IndexOutOfRangeException被拋出。記住這一點,當你創建和訪問一個數組。

+0

我是C#的新學習者。你可以給任何網站引用C#well.it是幫助增加我的知識。謝謝你,先生。 – SNP

+0

您可以參考此鏈接https://mva.microsoft.com/en-us/training-courses/c-fundamentals-for-absolute-beginners-16169?l=Lvld4EQIC_2706218949 –