Get the App
SLTechnology News&Howtos  ›  Development  › 

How to upload parameters to the Main method

Shulou Source: shulou.com Published: 2022-06-03 13:12:38 10月18日 Update

How to upload parameters to the Main method, I believe many inexperienced people are helpless about this, this article summarizes the causes and solutions of the problem, through this article I hope you can solve this problem.

Parameters can be sent 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 command-line arguments in the Main method in Windows Forms applications, you must manually modify the signature of Main in program.cs. The code generated by Windows Forms Designer creates Main with no input parameters. You can also use Environment.CommandLine or Environment.GetCommandLineArgs to access command-line parameters from anywhere in the console or Windows application.

The arguments to the Main method are String arrays representing command-line arguments. Generally, it is determined whether the parameter exists by testing the Length attribute, for example:

if (args.Length == 0) { WriteLine("Hello World. "); return 1; }

You can also use the Convert class or Parse method to convert string arguments to numeric types. 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 C#type long with alias Int64:

long num = long.Parse(args[0]);

You can also use Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);

example

The following example demonstrates how to use command-line arguments in a console application. The application takes a parameter at runtime, converts it to an integer, and calculates the factorial of that number. If no arguments are provided, the application issues a message explaining 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

Tags: Parameters methods programs applications applications commands content console more examples forms types problems faceted control helpless for this code location reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker vpn Apple OPPO Reno