[C #] basic knowledge

Source: Internet
Author: User
    • Scope and access level of Variables
    • Declare variables of various data types
    • In C #ProgramControl execution flow
    • Annotations and XML document blocking instructions
    • Preprocessor commands
    • Usage rules and naming rules (omitted)

 

1. Compile and run the C # program: Create the XX. CS file-> set the Environment Variable-> open the command line prompt-> cscxx. CS-> compileCode-> Automatically generate xx.exe. Note: two solutions without environment variables are available: (1) run the batch file % Microsoft Visual studio2005 % \ common7 \ tools \ vcvars32.bat on the command line before running CSC, microsoft Visual studio2005 is the installation directory for installing vs2005. (2) Start-> Program-> Microsoft Visual Studio 2005-> Microsoft Visual studiotools sub-menu-> Microsoft Visual Studio Command Prompt

2. the modifier static indicates that the method cannot be executed on a specific instance. Therefore, you do not need to instantiate the class before calling it.

3. variables:Datatype(Data Type)Identifier(Variable name)

Int I; the compiler does not allow us to use variables unless we initialize the I variable, but it allocates four bytes in the stack to save its value.

Variable initialization: (1) Value Type initialization: int I = 1; (2) reference type initialization: somethingobjsomething =NewSomething ();

4. variable scope: the code area of the variable that can be accessed

(1) variables with the same name cannot be declared twice in the same scope: for example, int I = 20;...; Inti = 30; is incorrect.

(2) The variable with the same name in the loop can be declared twice in the same scope: For (INT I = 0; I <10; I ++ ){...}; for (INTI = 9; I> = 0; I --){...}; is correct.

(3) variables with the same name can only be declared once in vitro, and cannot be declared again within the cycle.

(4) fields (variables declared as type-level variables) and local variables (variables declared as method-level variables) do not conflict in the same scope: classcar {staticInt I = 20; Public static voidmain (){Int I = 30; Console. writeline (I); return ;}}

How do I reference class variables? Object. fieldname (class name. Field name)

How to access the instance field (This field belongs to a specific instance of the class )? This. fieldname (this. Field name)

5. constants:ConstInti = 20; (the value is not changed during use ~, In C #, only the local variables and fields are declared as constants)

Constant features: (1) initialization when declaration is required, not modified after specified value (2) used for computation during compilation (3) constants are always static and do not need to be modified using static (4) replacing ambiguous numbers or strings with clear names that are easy to understand (5) makes the program easier to modify (6) avoids program errors.

6. predefined data types: Value Type (stored in the stack) and reference type (stored in the managed stack ).

Y = NULL; (indicates that no object is referenced). The basic data types int, bool, and long are value types; the complex type that contains many fields is specified as the reference type.

7. CTS type: (as described in the previous chapter) string S = I. tostring (); Inti = S. toint32 ();

 

8. predefined value types: Basic Data Type (integer, floating point type, character type, bool type) + reference type

(1) Basic data types:

INTEGER (8 ):Sbyte (system. sbyte) 8-bit signed integer, short (system. int16) 16-bit signed integer, INT (system. int32) 32-bit signed integer, long (system. int64) 64-bit signed integer, byte (system. byte) 8-bit unsigned integer, ushort (system. uint16) 16-bit unsigned integer, uint (system. uint32) 32-bit unsigned integer, ulong (system. uint64) a 64-bit unsigned integer. (Unsigned: 0 ~ 2n-1, signed:-2n-1 ~ 2n-1-1)

Uintui = 1234u; long l = 1234l; ulong ul = 1234ul;

Floating Point (2 ):Float (system. Single) 32-Bit Single-precision floating point number (n = 7 digits), double (system. Double) 64-bit double-precision floating point number (n = 15/16 digits ).

If the non-integer type is not specified, the default value is double. If you want to specify float, the final character F (or F) is added: floatf = 12.3f;

Decimal type (1 ):Decimal (system. decimal) 128-bit high-precision decimal notation (n = 28 digits), dedicated type and financial currency. Decimald = 12.30 M (numbers with higher precision)

Bool type (1 ):Bool (system. Boolean), the value is true or false. Note: The bool value and the integer value cannot be converted to each other.

Character Type (1 ):Char (system. Char) indicates a 16-bit Unicode character. Note: implicit conversion between the char type and the 8-bit byte type is not allowed. Although 8 digits are sufficient to encode each character in English and 0 ~ 9 digits, but they are not enough to encode every character (such as Chinese) in a larger symbol system. Therefore, with a 16-bit Unicode mode, ASCII encoding is a subset of Unicode. Chara = 'A' (single quotes instead of double quotes ). 4-bit hexadecimal Unicode value: '\ u0041'; integer with data type conversion: (char) 65; hexadecimal number: '/x0041 '.

Escape sequence: \ 'single quotation marks, \ ''double quotation marks, \ backslash, \ 0 blank, \ A warning, \ B Return, \ f form feed, \ n line feed, \ r carriage return, \ t horizontal tab and \ v vertical Tab

Note: C # has a string type, so you do not need to represent a string as an array of the char type.

(2) reference type:

Object (system. Object) root type. Other types in CTs are derived from it (including value type)

String (system. String) Unicode string

Note: stringfilepath = "C: \ procsharp \ first. cs" <=> stringfilepath = @ "C: \ procsharp \ first. cs"

@ Indicates that all characters are regarded as the original meaning and can also contain line breaks.

 

9. Flow Control: (1) Condition Statement:If (condition){Statement (s );},Else{Statement (s );}

If (condition1){Statement (s );},Else if (condition2){Statement (s );}...Elseif (condition n){Statement (s);} Statement (s );

Switch (condition) {CaseCondition1: Statement (s );Break;CaseCondition2: Statement (s );Break;...Default: Statement (s); break ;}

Note: The value of case must be a constant expression and variables cannot be used. During running, it disables all failed conditions. Only when the GOTO statement is used to specifically mark the case clause to be activated can the execution be continued and each case clause without a break be marked as an error. Solution: if a case clause is null, you can jump from this case to the next case, so that you do not need to use the GOTO statement to jump to the clause to generate non-logical errors. The case of different constants with the same value cannot be used, but the discharge sequence of constants with different values is irrelevant. Another function of the switch... case statement is to test variables using strings.

(2) loop statement: For Loop: For (INTI = 0; I <100; I ++ ){...}

The nested for loop is used to traverse each element in a rectangular multi-dimensional array. The most External Loop traverses each row, and the internal loop traverses each column on a row. The internal loop must be completely executed during each iteration of the External Loop. For (INTI = 0; I <100; I + = 10) {for (intj = I; j <I + 10; j ++) {...}...}

While loop: While (condition) Statement (s); Judge the loop condition first, and then execute the loop.

Do... while loop: do {...} while (condition); execute at least one loop first and then judge the loop condition.

Foreach loop: The total number of items in the iteration set.Foreach(InttempInArrayofints ){...}

Note: you cannot change the values of items in the Set (temp ).

(3) Jump statement: the GOTO statement cannot jump to a code block like a for loop or jump out of the class range. It cannot exit the Finally block after try... catch for exception handling. It is quite convenient to use the GOTO statement between switch... case statements. In other cases, the GOTO statement is not welcome.

Break statement: Exit various cycles, and then execute the following statements after the loop ends. If it is placed in a nested statement, the statement following the innermost loop is executed. If it is placed in the switch statement or external loop, the compilation is incorrect.

Continue statement: It must be used in various cycles. It only exits from the current iteration of the loop and re-executes from the next iteration instead of exiting the loop.

Return Statement: exit the method of the class and control the caller of the Return method. If there is a return value of the method, the return value of this type is returned.

 

10. enumeration: PublicEnumTimeofday {Morning= 0,Afternoon= 1,Evening= 2}, enumerative can call methods to execute useful tasks. Example: timeofdaytime =Timeofday. Afternoon; Console. writeline (Time. tostring());

Method for obtaining the enumerated value from a string: timeofdaytime2 = (timeofday)Enum. parse (typeof (timeofday), "Afternoon", true); console. writeline (INT) time2 );

Note: The first parameter: the type of enumeration to be used: typeof (enumeration class name), the second parameter to use the string, and the third parameter is bool to specify whether to ignore case sensitivity during conversion?Enum. parse () actually returns an object reference and explicitly converts this string to the desired enumerated type.

 

11. array: array name of the array type []

Initialize the array: int [] integers = new int [32]; note: the array always references the type, regardless of whether each element is a value type.

Access array element: integers [0] = 32; indicates that the value of the 1st array elements is 32.

Dynamically allocate the array memory location: int [] integers; integers = newint [32]; first, create an empty reference without initialization, then, use the new keyword to point this reference to the memory location requested for dynamic allocation.

View the number of elements in the array: intnumelements = integers. length;

12. namespace: namespacexx {class YY} <=> XX. yy

Note: The namespace is irrelevant to the Assembly. Multiple namespaces cannot be declared in another nested namespace.

13. Using statement: easy to use classes in other namespaces.

Namespace alias: Using alias AA = xx; Use the alias to instantiate a XX object X1: AA: XX X1 = new AA: XX ();

14. Main () method: the main program entry must be a static method of the class or structure, and the return type must be Int or void.

Public static intmain () {...} or public static void main () {...} or public static intmain (string [] ARGs ){...}

Compile multiple main () methods to make them the main program entry point: Use/Main, that is:Cscxx. CS/main: full name of the class to which it belongs

15. compile the C # file:/T: EXE console application (default),/t: Library Class Library DLL with a list,/t: module components without a list,/t: the C # file name,/reference, or/R output by the winexewindows application (without a console window)/out (assembly path and file name) references the type in the unreferenced assembly.

 

16. Console I/O: the specified value of console. Write () is written to the console, and a line break is added at the end of the output result of console. writeline ().

Formatted output: int I = 10; intj = 20; console. writeline ("{0} + {1} = {2}", I, j, I + J); {0} {1} {2} represents 1st, 2nd, 3rd parameters. You can also specify the width W: {n, w} to indicate that the width of the n-1 parameter is W. Adjust the position of the text in the width. positive values indicate right alignment, and negative values indicate left alignment. For example, the width of the first parameter of-{} left alignment is 2.

Pre-defined type Format String: C-local currency format D-decimal format (0 is added to the given precision specifier) E-scientific notation (INDEX ), the case (E, E) of the format string determines the case F-Fixed Point format of the index symbol. The precision specifier is set to the number of decimal places, which can be 0. g-normal format (the E and F formats depend on which formats are simpler) N-digit format (Use commas to represent the kilobytes) p-percentage format X-16 hexadecimal number format (the precision specifier is used to add the leading character 0). For example, C2 indicates the monetary unit of two decimal places.

 

17. Note: // single line comment ""

Description of XML document block Annotations: /// <C> mark the text in the line as Code </C> <code> MARK multiple lines as Code </code> <example> mark as a code instance </C>/ example> <exception> description of an exception class </exception> <include> comment line I containing other document description files </include> <list> INSERT LIST TO DOCUMENT description </List> <param> marking method parameters </param> <paramref> indicates that a word is a method parameter. </paramref> <permission> indicates access to members. </param>/ permission> <remarks> Add a description to a member </remarks> <returns> specify the return value of the method </returns> <see> Provide cross references to another parameter </See> <seealso> "see" in the description </seealso> <summary> provides a brief section about the type or member </Summary> <value> description attribute </value>

Compile and generate XML document description for the Assembly:CSC/T: Library/DOC: XX. xml XX. CS

Generate XX. XML Document Description: <? Xmlversion = "1.0"?> <Doc> <Assembly> <Name> XX </Name> </Assembly> <members> <membername = "T: namespace class name"> <summary>... </Summary> <returns>... </returns> <paramname = "AA"> </param> </members> where "T:" indicates a type, and "F:" indicates a field, "m:" indicates that this is a member.

 

18. C # Preprocessor command:

# Define debug defines the debug symbol, which is not part of the actual code but only exists when the compiler compiles the code.

# UNDEF debug deletes the definition of the symbol. If the symbol does not exist, # UNDEF does not work. If a symbol exists, # define does not work. # Define and # UNDEF commands must be placed in C #Source codeBefore declaring the code of any object to be compiled.

# If # Elif # else # endif Conditional compilation (check whether the symbol exists first. If so, only the code in the IF block is compiled. # If block, otherwise, all code will be ignored until a matching # endif command is encountered)

# Warning # error warning and Error Reporting compiling (use # error to check # Whether the define statement has done something wrong, and use # warning to remind you of what you have done)

# Region # endregion marks a piece of code as a piece of given name

# Line can be used to change the file name and row number information displayed by the compiler in the warning and error messages. # Line default can restore the row number to the default row number

# Pragma can suppress or resume specified compilation warnings, which can be executed on classes or methods, and more precise control of the suppression warning and Suppression Time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.