簡體   English   中英

c#命令行參數

[英]c# Command Line arguments

我試圖讓我的程序從命令行參數運行,所以我的代碼中有 3 個選項供您選擇運行。

問題是我想解析端口和參數,我該怎么做?

每個選項都有不同的程序配置。 我的嘗試如下所示; 所以在程序內部,我還想將端口作為參數傳遞,所以當我在控制台中編寫“程序 1 5656”時。 應用程序看到它運行的第一個選項 1,然后將 5656 解析為端口變量。

我在下面嘗試過,但是當我輸入命令時,它給了我錯誤的選項,因為它開始選項 2 而不是 1。

class MainClass
{
    static void Main(string[] args)
    {
        // Test if input arguments were supplied:
        if (args.Length == 1)
        {
            int port = int.Parse(args[1]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
        if (args.Length == 2)
        {
            int port = int.Parse(args[2]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
        if (args.Length == 3)
        {
            int port = int.Parse(args[3]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
    }
}

看來,您希望port最后一個參數:

  static void Main(string[] args) {  
    // if we have parameters...
    if (args.Length > 0) { 
      //TODO: int.TryParse is a better choice
      int port = int.Parse(args[args.Length - 1]); // ... port is the last one
      server = new TcpListener(IPAddress.Any, port);
      // Rest of the program
    }
  }

編輯 :如果您只想傳遞兩個參數optionport

  static void Main(string[] args) { 
    if (args.Length == 2) {
      //TODO: int.TryParse is a better choice 
      int option = int.Parse(args[0]);
      int port = int.Parse(args[1]);

      // Rest of the program, e.g.
      if (option == 1) {
        ...  
      } 
      else if (option == 2) {
        ...
      }
      else if (option == 3) {
        ...
      }   
    }
  }

這是你想要的嗎?

class MainClass
{
    static void Main(string[] args)
    {
        // Test if input arguments were supplied:
        var switchvalue = int.Parse(args[0]);
        if (switchvalue == 1)
                {
            int port = int.Parse(args[1]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
        if (switchvalue == 2)
        {
            int port = int.Parse(args[1]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
        if (switchvalue == 3)
        {
            int port = int.Parse(args[1]);
            server = new TcpListener(IPAddress.Any, port);
            //Rest of the program
        }
    }
}

在此處輸入圖片說明

public Main (string[] args)
{
   Console.WriteLine(args);
   Console.ReadLine();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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