Talking about the parameters of the Main method, and talking about the parameters of the Main method
You can send parameters to the Main method by defining the method in one of the following ways.
static int Main(string[] args)
static void Main(string[] args)
[Note] to enable the command line parameter in the Main method of the Windows Forms Application, you must manually modify the Main signature in program. cs. The code generated by the Windows Form Designer is created without the input parameter Main. You can also use Environment. CommandLine or Environment. GetCommandLineArgs to access command line parameters from any location in the console or Windows application.
The Main method parameter represents the String array of the command line parameter. Generally, you can test the Length attribute to determine whether a parameter exists. For example:
if (args.Length == 0) { WriteLine("Hello World."); return 1; }
You can also use the Convert class or Parse method to Convert string parameters to numerical values. For example, the following statement converts a string to a long number using the Parse method:
long num = Int64.Parse(args[0]);
You can also use the C # type long with the alias Int64:
long num = long.Parse(args[0]);
You can also use the Convert method ToInt64 to do the same job:
long num = Convert.ToInt64(s);
Example
The following example shows how to use command line parameters in a console application. The application uses a parameter at runtime to convert the parameter to an integer and calculate the factorial of the number. If no parameter is provided, the application sends a message to explain the correct usage of the program.
public class Functions { public static long Factorial(int n) { if ((n < 0) || (n > 20)) { return -1; } long tempResult = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } return tempResult; } } class MainClass { static int Main(string[] args) { // Test if input arguments were supplied: if (args.Length == 0) { Console.WriteLine("Please enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } int num; bool test = int.TryParse(args[0], out num); if (test == false) { Console.WriteLine("Please enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } long result = Functions.Factorial(num); if (result == -1) Console.WriteLine("Input must be >= 0 and <= 20."); else Console.WriteLine("The Factorial of {0} is {1}.", num, result); return 0; } }
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!