switch语句-C#未知索引超出范围异常
本文关键字:范围 异常 索引 语句 -C# 未知 switch | 更新日期: 2023-09-27 17:59:52
我正在学习开关。。。case语句,我找不出下面的代码有什么问题。一旦我调试,我会回到visualstudio并给我一个错误。C sharp.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]
,假设数组中至少有一个项,并且引用不是null。这两件事都不能保证。进行一些错误检查会很好,您也可以在调用程序时向程序传递一个命令行参数。
Visual Studio在遇到异常时应该突出显示某一行。让我猜猜:这个?
int input = int.Parse(userInput[0]);
这与switch
语句无关,而是与Main()
的参数有关。它们从命令行到达那里,例如,当您通过键入来调用程序时
command some-parameter
在C:''命令提示符下,或者在查看项目的"属性"时可以在"调试"页中设置的命令行参数中。
必须使用命令行参数调用该程序。否则,userInput不包含任何元素。然后,userInput[0]将触发此错误。
顺便说一句,查看异常的堆栈有助于更容易地找到罪魁祸首。它会把你指向相应的线。