簡體   English   中英

索引超出數組范圍

[英]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();
        }
    }
}

問題是您沒有將任何參數傳遞給您的程序。 您可以通過從命令行運行程序來完成此操作,或者如果您通過 Visual Studio 運行此程序,則可以通過轉到項目屬性、選擇“調試”選項卡並將它們輸入到“開始選項”部分來設置要傳遞的參數.

Visual Studio 項目屬性

您必須檢查實際提供了多少命令行參數:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM