In C #, there are some knowledge points that I think are quite unique. These knowledge points are frequently used by me, but I still know little about them, so I learned through searching for materials, I have summarized and briefly described these unique knowledge points and hope to help you! The main knowledge points include: var keyword, try... catch... finally, foreach statement, arraylist class, # region... # endregion and so on.
I. var keywords
Implicit type. use VaR to declare any type of local variables. In C #, it is only a keyword and does not represent a new type. It is only responsible for telling the compiler that the variable needs to be inferred based on the initialization expression, it can only be a local variable. After var declares the variable, the variable type is determined and will not change. Example:
VaR STR = "Hello World"; // string type, equivalent to string STR = "Hello World" Var request = (httpwebrequest) webrequest. create (URL); // This is an example I used in HTTP network programming. var can be replaced by the httpwebrequest type.
Ii. Try... catch... finally
It is used to handle exceptions. There are usually three Exception Handling statements:
(1). Try... Catch; // handle exceptions
(2). Try... Finally; // clear an exception
(3). Try... Catch... Finally; // handle all exceptions
The try block contains code that is prone to exceptions. When an exception is thrown, the catch exception handler is caught. When an exception occurs in the try block, the catch exception handler is redirected. The catch is used for the exception handler, the common format is: Catch (exception class
Abnormal object instance ){...}
Example 1: (refer to "learning from scratch C #")
Int [] Nums = {1, 2, 4, 5, 6, 7, 8, 9}; // defines the integer array try {for (INT I = 0; I <= num. length; I ++) {console. write (Num [I]. tostring () + ") ;}} catch (exception ex) {console. write (ex. message. tostring (); // input Exception error}
An error occurred while capturing the try statement. Because the array index is traversed from 0, "<=" is used to traverse the array 10 times. If the array index is traversed once more, the index is out of bounds, jump to the catch statement and create an exception object ex and output the error message. Shows the running result:
Finally is used to clear resources that generate misallocation. Try .. catch .. even if an exception is thrown in a finally statement, the code in the Finally block is executed (always executed) to release resources from the program. Try .. catch .. when a finally statement captures, clears, and executes an application, it is executed no matter whether there are any exceptions. If an exception occurs, the execution sequence is try-> catch-> finally. If no exception occurs, the execution sequence is: try-> finally. The following is an example used in the actual project:
Example 2: (this is the code I wrote in C # Network Programming)
Try {stream = response. getresponsestream (); // get the response stream... // Specific communication browser operation} catch (exception MSG) {MessageBox. show (MSG. message); // Exception Handling} finally {stream. close (); // release resources: Close stream operations}
This is the result of an exception in the C # browser (disconnecting the network), as shown in:
Finally, it is important to note that processing exceptions will greatly reduce the performance, so do not use them in controlling normal program processes. If exceptions in code may be detected, replace try .. catch .. finally operation. For example, if the divisor cannot be 0 in the starting process, we can use if to judge that the division operation is not 0, so that the replacement is realized. (I will not introduce the custom exception throw here)
Iii. foreach loop statements
The foreach statement repeats an embedded statement group for each element in an array or object set to access the set cyclically to obtain the required information. You need to call the ienumerable interface in the format of foreach (Type Variable
In set ){... // Action} each time a variable is executed, an element operation in the set is taken in sequence. The main feature of foreach statements is that the Code is concise and efficient.
Example 1: (simple iteration of foreach statements)
Int [] Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // defines the integer array foreach (int I in Nums) {console. writeline (I); // loop output array} // equivalent to: For (INT I = 0; I <nums. length; I ++ ){...}
Note: If you use the foreach statement in the preceding one-dimensional or multi-dimensional array traversal, The foreach statement will automatically check the index of the array so that it will not encounter an out-of-bounds error. In the preceding array access, the for loop statement determines whether the valid values of the array index are out of the boundary (equivalent to the IF-else statement) every time it is executed. foreach avoids this situation from being relatively more efficient. At the same time, it is more convenient to operate foreach using multi-dimensional arrays. It only needs one loop, and the for statement needs to be executed in multiple loops.
Example 2: (multi-dimensional array comparison between foreach and for statements)
Int [,] intarray = new int [] {5, 2}, {1, 2}, {3, 4 }...} Foreach (int I in intarray) {console. writeline (I);} // The for statement requires two layers of loop execution for (INT I = 0; I <intarray. getlength (0); I ++) for (Int J = 0; j <intarray. getlength (1); j ++) console. writeline (intarray [I, j]);
The following is a simple application of the foreach statement in the actual project. The Code is as follows:
Example 3: (simple application of foreach statements in actual projects)
Int COUNT = 0; // record the number of selected objects public list <Object> aryrects; // store all rectangle objects public abstract class shape: object {...} // Shape class: whether the attribute protected bool bselected is selected by the mouse foreach (shape s in aryrects) {If (S. bselected) // if selected, Count + 1 {count ++ ;}}
This is a C # drawing software that allows you to move and delete images that have been left-clicked on a graph and its corresponding attributes. The running result is as follows:
Obviously, it is very difficult or even impossible to use for to implement the above functions. This is the benefit of foreach and the application in practical engineering. Note that the loop variable here is a read-only local variable. If you try to change its value or delete it, an editing error occurs.
Foreach (int I in Nums) {I ++; // you cannot modify the value of console. writeline (I);} // the error message it prompts is: I is a foreach iteration variable and cannot be assigned foreach (int I in Nums) {nums. remove (I); // The value console cannot be deleted. writeline (I );}This is just a simple understanding of foreach. Some of the knowledge points and ideas are also referenced in this article. This is a very good article about foreach statements. Thanks to the original author and Author: Author
The array size is usually fixed and cannot be changed. However, C # provides the dynamic array arraylist class to dynamically add, insert, or remove elements, allowing you to set the array size more flexibly. Before using this class, you must declare the system. Collections namespace. The attributes and methods of arraylist are as follows:
Arraylist attributes
(Because the distance between inserted tables using csdn is too large, I don't know how to set the line spacing. I changed it to the image format. Sorry !)
Common arraylist method tables
(The two tables above are converted from Sun jingrui's "learning C # From Scratch". They are a very good book. I suggest you read them and thank you for the author, his knowledge is referenced here)
Example:
Arraylist arylist = new arraylist (); For (INT I = 0; I <4; I ++) {arylist. add (I); // use the add method to add 4 elements} console. writeline ("the number of elements in the arraylist dynamic array is:" + arylist. count); // count attribute string [] STR = {"ABC", "XYZ"}; arylist. addrange (STR); // addrange (array name) adds all elements in the STR array to the console at the end of the arylist dynamic array. writeline ("the number of elements in the arraylist dynamic array is:" + arylist. count); arylist. removeat (1); // Delete the element whose index is 1 (starting from 0): Number 1 (second) arylist. remove ("ABC"); // Delete the console of the first "ABC" value. writeline ("traverse all elements in the output arraylist dynamic array"); foreach (Object List in arylist) // traverses all elements in the output dynamic array arylist {console. writeline (list. tostring ());}
Shows the output result:
V. # region... # endregion
In C #, the use of preprocessing commands can prohibit the compiler from compiling a part of the code, or prohibit the compiler from Code related to additional functions. The start of preprocessing commands is the # symbol, for example: # define, # UNDEF, # If, # Elif, # else, # endif, # warning, # error, # regoin, # endregion, # Line, # pragma. Here I want to talk about # region... # endregion usage.
# Region... # The endregion command is used to mark a piece of code to a block with a specified name to expand or collapse the code block. # The region block must be terminated with the # endregion command. Format: # Region
The name... # endregion. is shown in:
# Region properties // operation menu corresponding to State Processing private contextmenu menudelset; private menuitem menuset; private menuitem menudel; private menuitem dynamicmodel; Public loaddata; public list <Object> aryrects; // store all the rectangle objects in the private list <Object> arylines; // store all the line objects in the public list <varbase> varlist; // store all the variables in the private list <int> usedmodelid; // used model ID private list <int> tousemodelid; // available model ID // undo or redo specifies that only five private undobuffer undob is saved; private shaperect grect = NULL; // The unique model selected in form; private shaperect gfrom = NULL; private shaperect GTO = NULL; // from and to private shapeline Gline = NULL when draw a line; private point firststart; private point laststart; // record the private const int irectw = 80; // The width of the State object rectangle; private const int irecth = 40; // The height of the rectangle of the State object; # endregion
Its advantage is that it can be recognized by some compilers, including Visual Studio.. Net compilers. These compilers can use these commands to make code layout on the screen better and hide the code for ease of management and viewing, as shown in, an example of hiding some functional code in the project gives you a clear picture.
I hope these knowledge points can help to consolidate and learn C # knowledge. At the same time, this is only a special knowledge point that I have encountered in learning C #. If there are any mistakes or deficiencies in the description, please forgive me! It is not easy to typeset. Sorry!
(By: eastmount, January 25Http://blog.csdn.net/eastmount/)