Chapter 3 C # core programming structure 1
This chapter describes some basic syntaxes and types of C. First, we introduced the application objects that all applications must use and their entry point functions (Main), then introduced some built-in data types, and then introduced the concepts of data conversion, finally, we introduce core operators, loops, and selection structures.
3.1 Main Function
By default, when a project is created, VS creates a default class called program (which can be renamed). This class contains a static function: Main, this function is the entry point for all executable applications (that is, when the program is executed, it is executed from this Main ), every executable application (console program, winform, and windows Service) must contain a class that defines the Main method!
The class that defines the Main method is calledApplication Object. Note that when there is only one application object, the compiler automatically recognizes and defaults it to the class where the entry point function is located. At the same time, there can be multiple application objects, that is to say, multiple classes can contain Main. However, this will confuse the compiler and do not know from which class to start. Therefore, you must specify one class as the entry point function, otherwise, compilation fails! The specified method (if there are multiple Main in a class, it is obviously not possible to compile it, because it is also possible to specify a class, rather than the specific Main method in a class ):
If the csc compiler is used, the main parameter is used;
If you use the vsplatform, select an application class from the project-properties-application "Startup object" drop-down box.
The Main function signature (method name, return type, parameter list) can be in four forms:
Static void Main (string [] args) {}// default static void Main () {} static int Main (string [] args) {} static int Main (){}
NOTE: If no explicit access modifier is provided, the Main method is automatically defined as implicit private, so that other applications cannot directly call the entry point of another application.
In summary, the Main can return either void or int type, and the parameters can be either (String Array) or not.
About the return type: Even if void is used, the system will return a value (0 indicates normal operation, and-1 indicates abnormal operation). This is a special feature of Main. If other common methods are void, there is no way to return values. In windows, the return value of the application is saved in the system variable of % errorlevel %, and this value is passed to the system variable only when the program ends. Therefore, the program cannot obtain its own value at runtime. Obviously, it can only be obtained by another program. For example, another program can start this program, you also need to determine whether the program is executed normally. YesSystem. Diagnostics. Process. ExitCodeTo obtain the system variable.
Usage:
Process myProcess = null; myProcess = Process. Start ("NotePad.exe"); // Start the notepad program. MyProcess. WaitForExit (); // be sure to wait for the process to end; otherwise, an error will be reported in the next sentence, because no ExitCodeConsole. WriteLine (myProcess. ExitCode) is returned if the process is not exited );
About parameters: the Main parameter is used to run the program normally. For example, run csc/t in dos, and the csc above is the Main program, the following/t is the parameter (which splits the string after the program name after the command is input with spaces). In the main program, different codes should be executed according to different parameters, in fact, parameter transmission does not have to be "-" or "/". It depends on the developer who responds to the command line parameters and how the parameters are formatted, can the parameter be set to csc? T, as long as the program can understand and process it.
In additionSystem. EnviromentStatic Method GetCommandLineArgs (), which can access the parameters entered when the user starts the program. Even if our Main is defined as a non-parameter format, it can be obtained. This method returns a string array of user input parameters. The first index is the application path and name, followed by the command line parameter. The method is as follows:
// Note: static int Main () {// use System. Environment to obtain the parameter. String [] theArgs = Environment. GetCommandLineArgs (); foreach (string arg in theArgs) Console. WriteLine ("Arg: {0}", arg); Console. ReadLine ();}
Please refer to the execution of this program and the returned results:
In addition, when using the vsplatform, to facilitate testing programs using different Command lines, you only need to enter the corresponding parameters in the following Command Line arguments. When the program is started, the following parameters are automatically entered.
Appendix: we can see that,System. EnviromentClass has many useful methods to obtain a large number of. NET ApplicationsOperating system details. You can view the SDK, which is a very useful class.
Q: What are the differences between System. Diagnostics. Process. ExitCode and System. Enviroment. ExitCode?
3.2 System. ConSole class
This is the most common class in the console program. It encapsulates input, output, and error stream operations based on the console application. You can refer to the SDK, which is mainly the write * and read * Members.
In the console, you can control the output format, using placeholders .. NET introduces a new string formatting style, similar to the C language printf () statement. In short, if you need to define a string text that contains some data fragments that need to be known for its value at runtime, you can use the curly braces syntax to specify placeholders within the text. At runtime, the value is passed in to Console. WriteLine () to replace each placeholder. This function is also widely used in string. format.
Note: If the number of placeholders in braces is inconsistent with the number of filled parameters, a FormatException exception will be received at runtime.
If the numeric data requires more detailed formatting, each placeholder can (optional) contain different format characters. The given placeholder value is marked with a colon and uses these characters as the suffix (for example, {0: C}, {1: d}, {2: X }).
3.3 Data Type
The C # keyword is not only a simple identifier that can be recognized by the compiler, but also a simplified symbol of the complete Type in the System namespace. For example, the keyword int is actually a system. int3's simplified flag. Therefore, either of the following methods can be used to declare the Data Type:
Int;
System. int32 B;
Note that, by default, a real value literal on the right of the value assignment operator is treated as a double type. Therefore, to initialize a folat variable, the suffix f or F is used. For example:
Double a = 5.3;
Folat B = 5.3F;
For any type (Value Type and reference type), it must be assigned a value before it can be used (otherwise, an error occurs during compilation). There should be two steps (which can be implemented using one statement). The first step is to declare, for example, int a; object B. In the second step, there are two methods to assign values to the value type. The first method is to assign values directly, for example, a = 1, because built-in data types support Default constructors, you can use new to automatically set variables to default values, for example, a = new a (). For reference types, you can assign values using the new constructor. By default, the value is null:
In this way, before using a value type (similar to a reference type), you should go through the following process:
Int a = 2; // declaration, direct value assignment
Int B = new B (); // declares that the default value is 0;
The built-in data types support many useful attributes and methods:
Numeric data type:All numeric data types have the MaxValue and MinValue attributes and are given a storage range. The double and float attributes also have the epsilon (smallest positive number) and infinity (positive and negative) attributes.
Console. WriteLine (int. MaxValue );
Bool type:Supports the TrueString and FalseString attributes and returns True and False strings.
String a = bool. TrueString;
Char type:You can use the dot operator To check which static methods are useful for char (Is * Is used To determine whether data Is in a certain range and To * Is converted To an equivalent)
String type:It provides many useful methods, including returning the length of a string, searching for the substring of a string, and converting the case. Remember that the "+" symbol in c # will be processed by the compiler as a call to the String. Concat method, reducing the input.
C # string constants contain various escape characters to limit how string data is output. Each escape character starts with a backslash followed by a special mark, such as "\ r", which is equivalent to entering a carriage return and other escape characters. For more information, see the relevant documentation.
In addition, C # introduces the @-Prefix string literal notation, which is called a verbatim string. It can invalidate the processing of a literal Escape Character and output the string. For example, if we want to output the \ n string, instead of escaping it as a carriage return, it should be @ "\ n". At this time, the system does not think this is an escape character, but directly outputs this string.
Equality of strings:We know that the string is the reference type, and the comparison of the reference type (= ,! =) They compare whether their references (pointers) are consistent. However, for strings, if this is not the case, he will redefine the equality operator as the value of the comparison string object, rather than the objects they reference in the memory, this is a special point to remember.
Immutable character strings:That is, once the string type is assigned a value, the value remains unchanged. Some people may say that the string can be changed. A string is often changed in the code, for example:
String a = "ABC ";
A = a + "DEF ";
It seems that a is changed to "ABCDEF", but in fact, this a has been reassigned (a new instance ), the previous position of a is still "ABC", but now it is unavailable and it will be recycled at an uncertain time. From this we can see that the string type requires frequent operations, so improper use will make the program inefficient, code expansion, especially involving string change operations.
To solve the performance problems caused by frequent string changes ,. NET provides the System. in the Text namespace, there is a StringBulider class. Its unique feature is that when a Member of this type is called, the internal character data of the object is directly modified, instead of obtaining data copies in the modified format.
Note that the stringbuilder type default constructor can only store strings of less than 16 strings. You can use other constructor to change the initial value. When the append string exceeds the limit, it copies the data to the new instance and expands the buffer according to the limit.
Question: In stringbuilder, "when the append string exceeds the specified limit, he will copy the data to the new instance and expand the buffer according to the specified limit ." Re-copy to the new instance indicates that the change operation is the same as the string operation. That is to say, if each operation exceeds the minimum limit, is it the same as the Code expansion problem caused by string? In addition, what is the limitation?
3.4 Data Conversion
To put it simply, data conversion can be divided into width conversion and narrow conversion.
Width conversion is used to define implicit "upward conversion" without causing data loss. During calculation or value assignment, the system automatically performs this conversion, for example:
Short a = 3;
Int B =;
Narrow conversions are downward conversions, and CLR cannot apply narrow operations, even if narrow conversions can be inferred (for example, assigning an int value within the short range to the short type ), this may also cause compilation errors. Because c # is type-safe, to forcibly narrow the conversion, you must use the operator () to forcibly convert the display, for example:
Int a = 2;
Short B = (short);
It should be noted that even if this forced conversion is used, no errors will occur during compilation. However, there is no guarantee that the converted result is what you want. Once the conversion is out of the range of the target type, the conversion result is unpredictable. To ensure that the forced conversion result is correct, c # provides the checked and unchecked keywords, which will ensure that data loss will certainly be detected.
When the checked keyword is used, the statements (statement blocks) contained by the checked keyword will get a runtime exception if the conversion overflows, this allows you to discover possible conversion errors (it is best to catch them with try catch), such:
Int a = 65530;
Shrot B = checked (short) a); // statement
Or checked // statement Block
{
Short B = (short);
}
To detect the overflow of each switch in the entire project, you can set it at the project level by project properties-generate-advanced, and select "overflow/underflow of detection operations ". This is actually the choice of the checked flag of the csc parameter in the compiler.
However, it should be noted that the overflow detection of the entire project consumes a certain amount of performance. Therefore, After all overflow exceptions are solved (it seems difficult ~~~, This checked flag can be disabled for static code detection and dynamic input.
In addition ,. NET provides the Convert method for conversion (width, narrow), the advantage is that it provides a language-independent method for data type conversion, the Parse method is also provided for converting the string type to various basic types. There are many comparative articles on the Internet that compare the forced conversion of parentheses, Convert, and Parse conversion, which will not be described here.
3.4 iteration and selection Structure
C # provides four types of iteration structures:
- For
- Foreach/in
- While
- Do/while
There are two condition structures:
The basic syntax is not mentioned, so pay attention to the following:
The while is similar to the do/while loop. The difference is that the latter loop will certainly execute the corresponding code block at least once (in contrast, if the initial termination condition is false, it is very likely that the while loop will not be executed ).
Do/while, don't forget to add a semicolon!
Do
{
// Something
}
While (xxxx); // note the semicolon!