为什么此代码显示错误?
问题描述:
// 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 thenarg[]
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[^]