如何在 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-06-21

292 瀏覽量

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.