[英]C# unknown index out of range exception?
我正在学习 switch...case 语句,但我无法找出以下代码有什么问题。 一旦我调试我回到视觉工作室并给我一个错误。 CSharp.exe 中发生类型为“System.IndexOutOfRangeException”的未处理异常
附加信息:索引超出数组范围。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C_sharp
{
class Program
{
//this will demonstrate the switch statement
static void Main(string[] userInput)
{
int input = int.Parse(userInput[0]);
switch(input)
{
case 1:
Console.WriteLine("you typed 1 (one) as the first command line argument");
break;
case 2:
Console.WriteLine("you typed 2 (two) as the first command line argument");
break;
case 3:
Console.WriteLine("you 3 (three) as the first command line argument");
break;
}
}
}
}
userInput[0]
,您假设该数组中至少有一项并且引用不为空。 这些东西都不能保证。 一些错误检查会很好,您也可以在调用它时将命令行参数传递给程序。
Visual Studio 应该在遇到该异常时突出显示特定行。 让我猜猜:这个?
int input = int.Parse(userInput[0]);
这与switch
语句无关,而是与Main()
的参数有关。 那些从命令行到达那里,例如当您通过键入调用程序时
command some-parameter
在 C:\\ 命令提示符下,或从命令行参数中,当您查看项目的属性时,您可以在“调试”页面中设置这些参数。
您必须使用命令行参数调用该程序。 否则, userInput 不包含任何元素。 然后, userInput[0] 将触发此错误。
顺便说一句,它有助于查看异常的堆栈跟踪以便更轻松地找到罪魁祸首。 它会将您指向相应的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.