为什么此代码显示错误? [英] Why does this code shows error?

查看:78
本文介绍了为什么此代码显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Namespace Declaration
using System;

// Program start class
class NamedWelcome
{
    // Main begins program execution.
    static void Main(string[] args)
    {
        // Write to console
        Console.WriteLine("Hello, {0}!", args[0]);
        Console.WriteLine("Welcome to the C# Station Tutorial!"); 
    }
}





每次我在visual studio中启动此代码时,都会发出错误!



ConsoleApplication1.exe中发生未处理的System.IndexOutOfRangeException类型异常



附加信息:索引超出了数组的范围。




我无法理解为什么会发生这种情况?

我是一个newbee到c#所以请帮助!!



Every time i fire up this code in visual studio, it shoots an error!

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication1.exe

Additional information: Index was outside the bounds of the array.


I couldnt understand why does this happens?
I am a newbee to c# so please help!!

推荐答案

如果你正在执行没有参数的程序,那么 arg [] 将为空,您将获得该异常。



尝试从命令行运行:

If you are executing the program without arguments then arg[] will be empty and you will get that exception.

Try running like this from the command line:
c:\>yourprogram.exe abhinav



或将您的代码更改为:


or change your code to:

if(args.length >0)
        Console.WriteLine("Hello, {0}!", args[0]);
else
        Console.WriteLine("Please supply an argument when executing.");


解决方案1非常好。有关详细信息,请参阅此处:

命令行参数教程 [ ^ ]

Main()和Command -Line Arguments(C#编程指南) [ ^ ]

命令行参数(C#编程指南) [ ^ ]

CP知识库:

C#中的自动命令行解析 [ ^ ]

C#/ .NET命令行参数解析器 [ ^ ]
Solution 1 is very good. For further information, see here:
Command Line Parameters Tutorial[^]
Main() and Command-Line Arguments (C# Programming Guide)[^]
Command-Line Arguments (C# Programming Guide)[^]
CP Knowledge Base:
Automatic Command Line Parsing in C#[^]
C#/.NET Command Line Arguments Parser[^]


这篇关于为什么此代码显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆