简体   繁体   English

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

[英]C# unknown index out of range exception?

I was learning about the switch...case statement and i cant find out whats wrong with the following code.我正在学习 switch...case 语句,但我无法找出以下代码有什么问题。 Once i debug i goes back to visual studio and gives me a error.一旦我调试我回到视觉工作室并给我一个错误。 An unhandled exception of type 'System.IndexOutOfRangeException' occurred in C sharp.exe CSharp.exe 中发生类型为“System.IndexOutOfRangeException”的未处理异常

Additional information: Index was outside the bounds of the array.附加信息:索引超出数组范围。

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] , you're assuming that array has at least one item in it and the reference isn't null. userInput[0] ,您假设该数组中至少有一项并且引用不为空。 Neither of those things are guaranteed.这些东西都不能保证。 Some error checking would be good, you could also just pass a command line argument to the program when you invoke it.一些错误检查会很好,您也可以在调用它时将命令行参数传递给程序。

Visual Studio should be highlighting a particular line when it hits that exception. Visual Studio 应该在遇到该异常时突出显示特定行。 Let me guess: this one?让我猜猜:这个?

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

That's nothing to do with the switch statement, but to do with the arguments to Main() .这与switch语句无关,而是与Main()的参数有关。 Those get there from the command line, for example when you invoke your program by typing那些从命令行到达那里,例如当您通过键入调用程序时

command some-parameter

at the C:\\ command prompt, or from your Command line arguments which you can set in the Debug page when you look at the Properties of your project.在 C:\\ 命令提示符下,或从命令行参数中,当您查看项目的属性时,您可以在“调试”页面中设置这些参数。

You must call that program with commandline arguments.您必须使用命令行参数调用该程序。 Otherwise, userInput does not contain any element.否则, userInput 不包含任何元素。 Then, userInput[0] will trigger this error.然后, userInput[0] 将触发此错误。

BTW, it helps to look at the stacktrace of the exception in order to find the culprit more easily.顺便说一句,它有助于查看异常的堆栈跟踪以便更轻松地找到罪魁祸首。 It would have pointed you to the corresponding line.它会将您指向相应的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM