[英]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.