简体   繁体   English

小程序抛出 IndexOutOfRangeException

[英]Trivial program throws IndexOutOfRangeException

I am getting an error when running the above code and don't know the exact issue.运行上述代码时出现错误,但不知道确切的问题。 What is the solution for this?解决这个问题的方法是什么?

using System;

class second
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, {}!", args[0]);
        Console.WriteLine("Welcome to the C# station tutorial!");

        Console.ReadLine();
    }
}

The error is "Index out of range" .错误是“索引超出范围”

你缺少参数位置

Console.WriteLine("Hello,{0}!", args[0]); 

The string[] args parameter is the command-line parameters to the exe. string[] args参数是 exe 的命令行参数。 I'm guessing that you didn't pass any arguments, therefore args[0] is out of range , just like it said.我猜你没有传递任何参数,因此args[0]超出范围,就像它说的那样。 If you ran your exe as:如果您将 exe 运行为:

your.exe MyName

then it would have at least got past the IndexOutOfRangeException - to raise a FormatException instead ;p To fix that, change the {} to {0} .那么它至少会超过IndexOutOfRangeException - 而是引发FormatException ;p 要解决这个问题,请将{}更改为{0}

This is what worked for me.这对我有用。 Check to make sure that there are parameters.检查以确保有参数。 If not, provide feedback on the console.如果没有,请在控制台上提供反馈。

        if (args.Length == 0)
        {
            Console.WriteLine("No input parameters were received.");
            return;
        }

I believe you ran the program off Visual Studio and thus had run the program without passing in any parameter against arg[] .我相信您在 Visual Studio 上运行了该程序,因此在没有针对arg[]传递任何参数的情况下运行了该程序。

To pass in a parameter Eg Scott to arg[] ,要将参数( Eg Scott to arg[]传递Eg Scott to arg[]

  1. go to the Solution Explorer (menu ViewSolution Explorer )转到解决方案资源管理器(菜单视图解决方案资源管理器

  2. select Properties .选择属性

  3. Input "Scott" into the "Command Line arguments" textbox under the Start Options section.开始选项”部分下的“命令行参数”文本框中输入“Scott”。

    The program will run as normal.该程序将正常运行。 See the image below.见下图。

乙

If args has zero items, then attempting to get the first index of it (ie 0) will cause an index out of bounds exception.如果 args 有零个项目,则尝试获取它的第一个索引(即 0)将导致索引越界异常。 You should check that args isn't null or empty before attempting to reference an index within it.在尝试引用其中的索引之前,您应该检查 args 是否不为 null 或为空。 If you ran that example with some command line arguments it would probably work.如果您使用一些命令行参数运行该示例,它可能会起作用。

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

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