What is “string[] args” in Main class for?

后端 未结 8 1504
眼角桃花
眼角桃花 2020-12-13 01:37

In C# the Main class has string[] args parameter.

What is that for and where does it get used?

8条回答
  •  抹茶落季
    2020-12-13 02:03

    From the C# programming guide on MSDN:

    The parameter of the Main method is a String array that represents the command-line arguments

    So, if I had a program (MyApp.exe) like this:

    class Program
    {
      static void Main(string[] args)
      {
        foreach (var arg in args)
        {
          Console.WriteLine(arg);
        }
      }
    }

    That I started at the command line like this:

    MyApp.exe Arg1 Arg2 Arg3

    The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".

    If you need to pass an argument that contains a space then wrap it in quotes. For example:

    MyApp.exe "Arg 1" "Arg 2" "Arg 3"

    Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:

    Copy.exe C:\file1.txt C:\file2.txt

提交回复
热议问题