Console app arguments, how arguments are passed to

2019-03-11 19:44发布

This would be question from c# beginner. When I create console application I get Main method with parameter args as array string. I do not understand how this method is called by system and how args are passed to the Main method. Maybe someone could explain? Is Main method are overridden of some kind of console class?

namespace ConsoleApplication1
{
    class Program
    {    
        static void Main(string[] args)
        {    
        }
    }
}

11条回答
Anthone
2楼-- · 2019-03-11 19:46

you can pass also by making function and then in this function you call main method and pass argument to main method

static int Main(string[] args)
    {


        foreach (string b in args)
            Console.WriteLine(b+"   ");

        Console.ReadKey();
        aa();
        return 0;

    }
    public static void aa()
    {
        string []aaa={"Adil"};

        Console.WriteLine(Main(aaa));
    }
查看更多
Juvenile、少年°
3楼-- · 2019-03-11 19:47

The args can be passed via command line and there can be no args as well.

查看更多
男人必须洒脱
4楼-- · 2019-03-11 19:55

The Main method is the Entry point of your application. If you checkout via ildasm then

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint

This is what helps in calling the method

The arguments are passed as say C:\AppName arg1 arg2 arg3

查看更多
闹够了就滚
5楼-- · 2019-03-11 20:00

Every managed exe has a an entry point which can be seen when if you load your code to ILDASM. The Entry Point is specified in the CLR headed and would look something like this.

enter image description here

查看更多
女痞
6楼-- · 2019-03-11 20:00

Read MSDN.

it also contains a link to the args.

short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.

if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)

in the main you will need to read those args for example:

for (int i = 0; i < args.Length; i++)
{
    string flag = args.GetValue(i).ToString();
    if (flag == "bla") 
    {
        Bla();
    }
}
查看更多
何必那么认真
7楼-- · 2019-03-11 20:04

All answers are awesome and explained everything very well

but I just want to point out differant way for passing args to main method

in visual studio

  1. right click on project then choose Properties
  2. go to debug tab then on the start options section provide the app with your args

like this image

Properties window

and happy knowing secrets

查看更多
登录 后发表回答