索引在C#控制台应用程序中超出数组错误的范围 [英] Index was outside the bounds of the array error in C# console application
问题描述
可能已经有类似的问题,但是我想我在这里有一个特殊的情况
There might be similar questions already, but I think I have a specific case here
我试图了解现有应用程序的工作方式并立即对其进行调试
I'm trying to understand how an existing application is working and debugging it right now
这是一个控制台应用程序,我在其中提供6个参数:
It is a console application where I'm providing 6 parameters:
- 职位名称
- 布尔标志
- 文件位置
- 文件类型
- 日期
- FileAppID
我通过调试"下的命令行参数值提供参数列表.项目的一部分
I provide the list of parameters through the Command line arguments value under "Debug" section of the project
因此,它看起来像这样:" MyJobName""0"" C:\\ MyFile.txt""MyFileType""20200318""MyAppID"
So, it look something like that: "MyJobName" "0" "C:\\MyFile.txt" "MyFileType" "20200318" "MyAppID"
应用程序具有以下逻辑:
Application has the following logic:
SortedList<string, string> L = new SortedList<string,string>();
for (int i = 2; i <= args.GetLength(0) - 1; i++)
{
L.Add(args[i].Split(':')[0], args[i].Split(':')[1]);
}
List<SqlParameter> p = new List<SqlParameter>();
p.Add(new SqlParameter("@JobName", args[0]));
string xmlResult = D.RunProcedureXmlString("SPU_GetJobInfo", p);
因此,当我在第一次迭代中触及循环内部的行时,就会发生以下运行时错误:
So, when I hit the line inside of the loop on the first iteration, the following run time error happens:
args[i].Split(':')[1] 'args[i].Split(':')[1]' threw an exception of type 'System.IndexOutOfRangeException' string {System.IndexOutOfRangeException}
现有逻辑有什么问题,解决方案是什么?
What is wrong with the existing logic and what is the solution?
我不确定该修补程序是否会破坏我之前认为的工作.以后需要测试.
I'm not sure if the fix will break what I guess worked before. Will need to test it later.
推荐答案
如果 args
数组中的一项不包含:
字符,则调用 Split(':')
将返回仅包含一项的数组.因此,调用 args [i] .Split(':')[1]
将引发 IndexOutOfRangeException
.
If one of the items in the args
array does not have a :
character in it, then calling Split(':')
will return an array with only one item. Therefore, calling args[i].Split(':')[1]
will throw an IndexOutOfRangeException
.
此外,您应该只调用一次 Split
,以便您可以重用结果数组,而不是浪费周期和内存多次调用.
Also, you should only call Split
once so you can re-use the resulting array, rather than wasting cycles and memory calling it multiple times.
解决此问题的一种方法是先检查字符串拆分结果是否具有所需的部分数量:
One way to resolve this issue is to first check to see if the result of splitting the string has the required number of parts:
for (int i = 2; i < args.GetLength(0); i++)
{
var result = args[i].Split(':');
if (result.Length < 2)
{
// Do something here if there aren't enough items
}
else
{
L.Add(result[0], result[1]);
}
}
或者如果没有足够的项目,则使用默认值:
Or use a default value if there aren't enough items:
for (int i = 2; i <= args.GetLength(0) - 1; i++)
{
var result = args[i].Split(':');
var firstPart = result[0];
var secondPart = result.Length > 1 ? result[1] : string.Empty; // Default value
L.Add(firstPart, secondPart);
}
这篇关于索引在C#控制台应用程序中超出数组错误的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!