[英]Index outside of the bounds of the array in a list
我有以下代碼:
public List<IAction> Dispatch(string[] arg)
{
int time=0;
int i = 0;
int j = 0;
List<IAction> t = new List<IAction>(10);
do
{
if (arg[j][0] == '/') // I get index out of bounds here
{
Options opt = new Options();
time = opt.Option(arg[j]);
j++;
}
else
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
i++;
j++;
}
}
} while (i != arg.Length);
for (int z = 0; z < t.Count; z++)
{
((ComputeParam)t[z]).Time = time;
}
return t;
}
為什么會發生錯誤...我只是傳遞參數,如果它們是數字,我將它們添加到列表中,如果不是,我設置一個選項並繼續。 這里有什么問題?
編輯:我傳遞 2 /t:Med 2 3 這些是參數。 我已經檢查過它 arg[1](在本例中)為空,但事實並非如此。
我在這里看到幾個可能的問題:
arg[]
為空,您將得到異常arg[j]
是一個空字符串,你會得到異常j
正在遞增,但i
沒有。我認為這會解決它:
public List<IAction> Dispatch(string[] arg)
{
int time=0;
List<IAction> t = new List<IAction>(10);
for (int j = 0; j < arg.Length; j++)
{
if (!String.IsNullOrEmpty(arg[j]) && arg[j][0] == '/')
{
Options opt = new Options();
time = opt.Option(arg[j]);
}
else
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
// Don't need to increment i
}
}
}
for (int z = 0; z < t.Count; z++)
{
((ComputeParam)t[z]).Time = time;
}
return t;
}
當您嘗試索引一個沒有元素的元素時,您會得到這個,因為通常您在數組小於您預期時索引元素。
在您的情況下,要么:
j
的值大於或等於arg.Length
,因此arg[j]
超出范圍。arg[j]
中的字符串沒有字符,因此arg[j][0]
超出范圍。 您可以使用數組的Length
屬性測試長度。 string
也有一個Length
屬性。
順便說一句,你不會在所有情況下都增加j
並且你甚至似乎沒有使用i
除了在檢查中之外,但是j
可能比i
增加得更多意味着你的while (i.= args.Length)
不會保護您免受IndexOutOfBoundsException
的侵害。 另外,檢查至少應該是while (i < args.Length)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.