在 C# 中如何在 main 方法中傳遞命令列引數?


Main() 方法是入口點 −

static void Main(string[] args)

引數陣列 args 用於設定引數 −

string[] args)

如果您新增兩個引數,它將設定以下內容 −

var args = new string[] {"arg1","arg2”}

這是示例程式碼 −

示例

using System;

namespace Demo {
   class HelloWorld {

      // args for command line
      static void Main(string[] args) {
         Console.WriteLine("Welcome here!");
         Console.ReadKey();
      }
   }
}

要使用命令列而不是 Visual Studio IDE 編譯 C# 程式 −

  • 開啟文字編輯器並新增上述程式碼。

  • 將檔案另存為 helloworld.cs

  • 開啟命令提示符工具並轉到您儲存檔案所在的目錄。

  • 鍵入 csc helloworld.cs 並按 Enter 鍵編譯您的程式碼。

  • 如果您的程式碼中沒有錯誤,命令提示符將進入下一行並生成 helloworld.exe 可執行檔案。

  • 鍵入 helloworld 來執行您的程式。

  • 您會看到螢幕上列印的 Hello World 輸出。

更新於: 2020 年 6 月 21 日

292 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.