Section 2: read command line Input
Many programs can accept the command line input. The following program is to accept the command line input, and then print it to the console screen.
Program 1-2: NamedWelcome. cs
// Namespace Declaration
Using System;
// Program start class
Class NamedWelcome {
// Main begins program execution.
Public static void Main (string [] args ){
// Write to console
Console. WriteLine ("Hello, {0 }! ", Args [0]);
Console. WriteLine ("Welcome to the C # Station Tutorial! ");
}
}
Compile the program as namedwelcome.exe and enter "NamedWelcome Joe" in the command line ". Be sure to add the name or other information after the program name; otherwise, the program will fail. We will discuss how to detect and avoid such errors later.
In program 1-2, you can see that there is a parameter in the parameter list of the "Main" method, the name is "args", that is, the parameters used by the following program. "String []" is used to define the data type of a parameter as a string. It can contain one or more characters. Square brackets "[]" indicate that "string []" is an array that can contain multiple parameters. Therefore, the parameter can be one or more parameters from the command line.
You will notice Console. WriteLine ("Hello, {0 }! ", Args [0]); this line of program. This line of program is different from the previous one. A parameter "{0}" is added to the quotation marks }". In a WriteLine statement, the parameter represents a method like this. The format of the first parameter is "{0}", and the second parameter is "{1}", and so on. Here, "{0}" indicates that the content of "{0}" is determined by the parameter "args [0]" after the ending quotation mark. Based on this idea, let's take a look at the parameter "args [0]" after ending the quotation marks.
The "args [0]" parameter indicates the first element in the "args" array, and the second element is "args [1]", and so on. For example, if I enter "NamedWelcome Joe" in command line mode, the value of "args [0]" is "Joe"
Now let's look at this code again: Console. WriteLine ("Hello, {0 }! ", Args [0]); During execution," {0} "will be replaced by the value in the parameter" args [0] ", and" Hello, "output to the screen together. Therefore, when we enter "NamedWelcome Joe" during program execution, the following content will be output:
> Hello, Joe!
> Welcome to the C # Station Tutorial!