2. C # core programming structure,
For more information, see Andrew Troelsen's C # And. NET4 advanced programming, This section describes the following: Hello World Main method: Use VS2010 to create a console application Hello World, complete the Code as follows: class and Main method: here, the system automatically creates a class called Program, which has a default Main method. Here, the class name of our program can be modified arbitrarily, but the Main () method must be unique, and an error will occur after the modification. Because the Main () method is the entry to our application. The error message is as follows: the Main method is the entry to reference the program, and the processing logic is within the Main method. By default, a static void (null) return value is generated, and a parameter string array is accepted. However, this is not the only form of the Main method. In addition, we also have the following signature forms. If the defined entry function does not return NULL values, we must provide a return value at the end of the program. (Return value 0 indicates normal completion): static int Main (string [] args) {// processing logic return 0;} // No parameter return value static void Main () {} // no parameters return the value static int Main () {return 0;}. You can use System. environment class members. (Environment. GetCommandLineArgs (). This function returns a string array, which can be retrieved through traversal. System. Console class, which has the following three functions: 1. Basic input and output. The WriteLine method of the code above indicates that the output is in the console, while ReadLine indicates that the input is accepted. In addition, the Write and Read methods are used in a similar way. 2. Format console output. You can use placeholders for formatting, for example, Console. writeLine ("{0}, {1}", 123,456); The placeholder number corresponds to the order of the subsequent output parameters, starting from 0. And placeholders can be separated. 3. Format numeric data. Similar to % d in C and C ++, % x represents the output number and hexadecimal format, where D/d and X/x can be used. Usage: Console. WriteLine ("c format: {0: c}", 9999); 4. format numeric data outside the Console application. Use string. format () method to Format. Usage: string userNum = string. format ("100000 in hex is {0: x}", 100000); System Data Type and C # simplified Symbol: Same as any programming language, C # defines a set of basic data types used to represent local variables, member variables, return values, and input parameters. Such as bool, byte, short, int, and long. However, unlike other programming languages, these keywords are not just a simple identifier that can be recognized by the compiler. The C # data type keyword is actually a simplified symbol of the complete Type in the System namespace, for example, ulong is System. UInt64. Variable declaration and initialization: int myInt; string myString; you can assign a value directly to int myInt = 0 during initialization. Alternatively, int a = 1, B = 2, c =; built-in data types and new operators: All built-in data types support Default constructors, which can be created using new. For example, the bool type can also be represented as follows: bool B = new bool (); the hierarchical structure of the data type class :. net basic data types all have a class hierarchy. The type at the top of the tired hierarchy structure provides some default behavior for the derived type. The relationship between these core types is shown in: Member of the numerical data type: we must know to continue to study the data type of C.. net supports the MaxValue and MinValue attributes, which indicate the storage range of a given type. Usage: int. MaxValue, double. MaxValue, etc. System. Boolean Member: it does not support MinValue and MaxValue, because it can only come from the set {true | false }. However, the TrueString and FalseString attribute sets are supported (returns True or False accordingly ). System. Char member: the text data of C # is represented by the string and char keywords, both of which are Unicode-based. String indicates continuous characters, and char indicates a single character. Parse a value from string data (. Parse (): this technique is useful when you want to convert the data you enter into a value. Use int I = int. parse ("8"); System. dateTime and System. timeSpan: DateTime indicates the date and time, while TimeSpan allows you to easily use each Member to define and convert the time unit .. Net 4 System. Numerics namespace: it defines a BigInteger structure, used to represent a large value, it does not have a fixed upper and lower limit. Use string data: Basic string operation: string. Length to get the string Length, string. ToUpper to get the string to the upper-case value, string. ToLower to get the string to the lower-case value. String concatenation: string. Concat (), but we can also use the + number to represent concatenation. The compilation results are the same. Escape characters: like C, they are all backslash \, which can be expressed as special characters in C. Define a verbatim string: C # introduces a string literal excitation prefixed with @, which is a verbatim string. You do not need to use escape characters when using its strings. String and equality: Use the String Equals method or the embedded equal operator (=) to perform equality operations, this indicates case-sensitive, character-by-character equality operations, although the String type is a reference type. The string type is immutable: the method of the string type, imposing regret for a New string object in the modified format, the original string will not change. Therefore, if the string class is abused, it becomes inefficient and leads to code expansion, especially when string concatenation. (Because each operation will load a New String object on the hosting stack, the original string object will be eventually reclaimed) System. text. stringBuilder Type: this class and System. the String class is similar, but to prevent the inefficiency of the String class, StringBuilder defines many methods to replace and format fragments. It is unique in that when we call Members of this type, the character data inside the object is directly modified (so it is more efficient), rather than the data copy in the modified format. Narrow and wide data type conversion: the operations only seen in values and small values. Because C # is type-safe, there will be errors in narrow operations. However, you can narrow them by force conversion, however, this may cause data loss. The checked and unchecked keywords provided by C # will ensure that the data monk will certainly be detected. Usage of checked: Used in the following code: byte sum = checked (byte) Add (b1, b2); used in a statement block to check whether it is forced overflow: checked {byte sum = (byte) Add (b1, b2); Console. writeLine (sum);} the unchecked keyword is used in the same way as the checked keyword, except that it checks all the operation logic and runs out of language exceptions in some situations. System. Convert: One advantage of using it is that it provides language-independent methods for data type conversion (for example, VB type conversion is completely different from C #). Implicit local variable (var): C # Language defines a local variable that can use the var keyword to create an implicit type. You do not need to specify specific data types (such as int, bool, and string) when using the var keyword ). In doing so, the compiler will automatically deduce the actual data type based on the initial value class of the local data point. Usage: var myInt = 0; // defines an integer, and var is equivalent to intvar myBool = true; // defines a Boolean value. Var is equivalent to bool implicit type variables: first, the implicit type can only be used for local variables within the method or attribute range. Defining the return value, parameter, or custom type field data with the var keyword is invalid. Similarly, the local variable declared with the var keyword must be assigned an initial value at the time of declaration, and the initial value cannot be null. Finally, use C #'s? Marking and defining controllable implicit local variables is illegal. Implicit type data is strongly typed: implicit type variables affect the life of variables during compilation, and the data point will be considered as the life type, assigning different types to this variable will cause compilation errors. Implicit type variable usage: it will become very useful in the Linq query. C # iteration structure: for Loop. Similar to for loop usage in C and C ++, we can create complex termination conditions, create infinite loops, and use the goto, continue, and break keywords. Foreach/in loop: the C # foreach keyword allows you to traverse all the items in the array without testing the launch of the array. The foreach structure uses var. In this case, the compiler can accurately determine the exact type of this type. While and do/while loops: The while loop structure is useful when you want to execute a statement until a certain termination condition is met. Similar to a simple while LOOP, you can use the do/while loop when we need to patch the number of times. The difference between the two is that the do/while loop will certainly execute the corresponding code block at least once, while the while LOOP may end without execution. Condition structure and relationship/equal OPERATOR: if/else statement in C # can only apply to boolean expressions, and cannot be used for values such as-1 and 0, therefore, if/else statements usually contain some C # operators. (= ,! =, <,>, <=,> =, And logical operators &, |, And ,!). Note: & | operators are all short-circuited when necessary. That is to say, if an expression is determined to be false, other expressions will not be checked. Switch statement: similar to the C-series language, the switch statement allows us to process the program process based on the definition. C # each case (including default) must contain executable statements terminated with break or goto to avoid failure. Summary: This section describes the basic structure of each C # executable program and the details of some built-in data types in C. It also introduces the var implicit keyword and the conditions and iteration statements supported by C. In the next section, we will complete the research on the new language features.