[英]Index was out of the bounds of the array
这是我的程序有错误:
索引超出数组范围
代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace command
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("First Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}
}
}
您必须检查实际提供了多少命令行参数:
using System;
using System.Collections.Generic;
using System.Text;
namespace command
{
class Program
{
static void Main(string[] args) {
if (args.Length > 0)
Console.WriteLine("First Name is " + args[0]);
if (args.Length > 1)
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}
}
}
例如
# No parameters
c:\MyProgram.exe
# One parameter
c:\MyProgram.exe FirstNameOnly
# Two parameters
c:\MyProgram.exe FirstName LastName
这取决于您至少传递两个参数的想法,但您没有先验证这一点。 如果您不想要输出,除非用户满足至少两个参数,然后使用 try{} 块,并捕获越界数组并响应用户使用至少两个参数。
static void Main(string[] args) {
try{
Console.WriteLine("First Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}catch (OutOfBoundsException exception){
MessageBox.Show("Insufficient input parameters");
}
您还可以使用 if(args.Length == 2) 来确定这是否足够而不使用 try{}。
您必须始终检查 args 数组的大小。 所以...
static void Main(string[] args)
{
if ( args.Count() >= 2 )
{
Console.WriteLine("First Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}
}
尝试这个:
static void Main(string[] args)
{
if(args.Length > 0)
{
Console.WriteLine("First Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
}
else
Console.WriteLine("No Command Line Arguments were passed");
Console.ReadLine();
}
并按照David_001 的解释传递命令行参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.