我遇到了一個項目異常「System.IndexOutOfRangeException」,並在這裏隔離到這個示例代碼塊。索引超出了數組的範圍。但索引是在範圍
using System;
public class Program
{
public static void Main()
{
string testStr = "AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7";
//split testStr into substrings representing each edge
string [] edges = testStr.Split(", ".ToCharArray());
foreach(string edge in edges)
{
Console.Write(edge + "\n");
char [] cEdge = edge.ToCharArray();
char cost = cEdge[cEdge.Length - 1]; // what out of bounds?
Console.Write(cost);
}
}
}
此問題來自「char cost = cEdge [cEdge.Length - 1];」行。這對我來說沒有任何意義,因爲此時cEdge應該是一個長度爲3的數組。因此,在cEdge.Length - 1處的索引應該是索引2,並且位於數組的邊界內。我很困惑,也許我已經看過一些東西。感謝您的時間和幫助。
如果cEdge的長度爲零,那麼'cEdge [cEdge.Length-1]'將產生一個越界異常。 – dbc 2014-11-08 07:10:10