Console app arguments, how arguments are passed to Main method

前端 未结 10 1176
醉话见心
醉话见心 2020-12-08 09:30

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 t

相关标签:
10条回答
  • 2020-12-08 10:24

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-08 10:24

    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));
        }
    
    0 讨论(0)
  • 2020-12-08 10:26

    in visual studio you can also do like that to pass simply or avoiding from comandline argument

     static void Main(string[] args)
        {
            if (args == null)
            {
                Console.WriteLine("args is null"); // Check for null array
            }
            else
            {
                args=new string[2];
                args[0] = "welcome in";
                args[1] = "www.overflow.com";
                Console.Write("args length is ");
                Console.WriteLine(args.Length); // Write array length
                for (int i = 0; i < args.Length; i++) // Loop through array
                {
                    string argument = args[i];
                    Console.Write("args index ");
                    Console.Write(i); // Write index
                    Console.Write(" is [");
                    Console.Write(argument); // Write string
                    Console.WriteLine("]");
                }
            }
    
    0 讨论(0)
  • 2020-12-08 10:26

    Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.

    From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab

    0 讨论(0)
提交回复
热议问题