C#未知索引超出范围异常?

时间:2014-04-24 21:10:09

标签: c# switch-statement

我正在学习switch ... case语句,我无法找到以下代码的错误。一旦我调试我回到视觉工作室并给我一个错误。 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;
        }
    }
}

}

3 个答案:

答案 0 :(得分:2)

Visual Studio应该在遇到该异常时突出显示特定行。让我猜一下:这个?

int input = int.Parse(userInput[0]);

这与switch语句无关,而与Main()的参数有关。那些从命令行到达,例如当您通过键入

调用程序时
command some-parameter

在C:\命令提示符下,或者在查看项目属性时可以在“调试”页面中设置的命令行参数。

答案 1 :(得分:2)

userInput[0],您假设数组中至少有一个项目且引用不为空。这些都没有保证。一些错误检查会很好,你也可以在调用时将命令行参数传递给程序。

答案 2 :(得分:1)

您必须使用命令行参数调用该程序。否则,userInput不包含任何元素。然后,userInput [0]将触发此错误。

BTW,它有助于查看异常的堆栈跟踪,以便更容易地找到罪魁祸首。它会指向你相应的一行。