Pocket notes (1): C # key points of programming,

Source: Internet
Author: User
Tags finally block

Pocket notes (1): C # key points of programming,
Preface

The Pocket notes series focus on recording small technical points in daily life, although the relationship between points may not be very large. However, it is small enough to be familiar with and applied to the daily development cycle to produce practical benefits. Remember is the first step, not the ultimate goal. The ultimate goal is to develop a high-efficiency program that combines flexibility, scalability, and portability with an understanding of the principles. This series starts with a small knowledge point in C #, but it is not limited to a specific language in the future. The documents and books extracted from the daily work can be a summary of the things you have read. Some of them only give an outline or a conclusion. (Note: most of the points in this article need practical development experience to help you read and understand .)

Directory
  • Const and readonly
  • Is,
  • Conditional compilation # if # endif and Conditional features
  • Equality judgment
  • GetHashCode () trap
  • Delegate
  • Resource Management (GC, Terminator, IDisposable, and using)
  • Operation Sequence for creating the first instance
  • Compile Lifecycle
I. const and readonly

When the const of the compilation period is compiled into IL, it is replaced with the literal value. Therefore, to change the value of a public compile-time constant, you need to re-compile all codes that reference the constant to ensure that all codes use the latest constant value.

On the contrary, when the runtime is often compiled into IL, the readonly variable is referenced, instead of the variable value. You only need to re-compile the code that changes the constant value, to achieve compatibility with other released code at the binary level. Ii. is,

There are two situations:

The target type of the conversion is the reference type: use is to test whether the conversion is successful, and then use as for conversion (as returns null when the conversion object is null ). As and is do not perform user-defined conversions. The conversion is successful only when the runtime type is the target type or the derived type of the target. You can use force conversion to execute custom conversions. The target type of conversion is value type: as cannot be used, and forced conversion can be used. Iii. Conditional compilation # if # endif and Conditional are both suitable for routine debugging. # If can be interspersed with Conditional code in a function, but the Conditional feature can be used to separate Conditional code (such as DEBUG) at the function level to ensure a good structure of the Code. Iv. Equality judgment (1) Key Points of equality in mathematics: reflexive: indicates that any object is equal to itself, no matter what type of a is, true should be returned for a = a; symmetric Ric: it means that the order of equality judgment is irrelevant. If a = B, true is returned, if B = a, true is also returned. If a = B and B = c, true is returned, then a = c will certainly return true; the value is equal (corresponding to the value type): If the two value types have the same type and contain the same content, the value is "equal "; references are equal (corresponding to the reference type): If two variables of the reference type point to the same object, the references are equal. (2) C # the four methods for medium-same-sex judgment: public static bool ReferenceEquals (object left, object right). Whether compared with the value type or the reference type, this method is based on object identification. So it is used to compare two value types and the result will always be false, because it is packed. When creating your own classes, you almost do not need to override them. Public static bool Equals (object left, object right) This method is used to determine the runtime type of two variables. The internal implementation first references ReferenceEquals for judgment, then uses left, right, and null for judgment, and finally uses left. Equals (right) for judgment. When creating your own classes, you almost do not need to override them. Public virtual bool Equals (objcet rials) has two situations: For the reference type System. object: Use the Object identifier to determine whether the two objects are "referenced equal". By default, the two objects are exactly the same as ReferenceEquals. You do not need to override the new reference type. For the value type System. ValueType: overwrite the method in System. Object to determine whether the value is equal. Because the current specific value type cannot be known, reflection is used, which is less efficient. We recommend that you override this method when creating a value type, and overwrite the GetHashCode () method. Public static bool operator = (MyClass left, MyClass right) reference type System. Object: Use the Object ID for judgment. Value Type: System. ValueType: overwrites the method in System. Object. Because the current specific value type cannot be known, reflection is used, which is less efficient. We recommend that you override this method when creating a value type, and overwrite the GetHashCode () method. 5. The GetHashCode () Trap works properly in the reference type (System. Object), although it does not necessarily produce an efficient distribution. In the value type (System. valueType): GetHashCode () works normally only when the first field of struct is read-only. Only when the value contained in the first field has a relatively random distribution, getHashCode () generates an efficient hash code. GetHashCode overwrite Rule 6. Delegate built-in delegation form
  • Predicate <T>: a function that provides Boolean return values;
  • Action <T1, T2>: parameters for receiving any parameter;
  • Func <T1, T2, ResultT>: accepts zero to multiple parameters and returns a single result;
The. NET delegate is a multicast delegate. The multicast delegate combines all the target functions added to the delegate into a single call. There are two points to note: solution: traverse the call list and call each target function on the delegate chain. Delegate applied to callbackMethods that take Predicate, Action, and Func as parameters, such as List. find (Predicate <T> p); When a lambda expression is input, the compiler converts the lambda expression to a method, creates a delegate, points to the method, and calls the delegate to implement the callback. Delegate applied to event

The Event Mode of. NET is the observer mode.
Public event EventHandler <LoggerEventArgs> Log;
The compiler automatically creates code similar to the following and can write it as needed.
Private EventHander <LoggerEventArgs> log;
Public event EventHander <LoggerEventArgs> Log
{
Add {log = log + value ;}
Remove {log = log-value ;}
}
An event is equivalent to a delegate set, and multiple same-type delegates can be added (through + = );

The delegate can add multiple methods of the same type (via constructor or + =). 7. The memory on the Resource Management hosting stack is managed by GC (Garbage Collector, CLR contains GC, developers are responsible for other resources .. NET provides two mechanisms for managing the life cycle of unmanaged resources: finalizer (called by GC, called at a certain time after the object becomes garbage, unpredictable) and IDisposable interface. (1) GCGC can determine whether an object is still referenced by the activity object of the application. For those entities that are not directly or indirectly referenced by the activity object, GC judges it as garbage. GC compresses the managed heap during each running. The compressed managed heap can store the currently used objects in the continuous memory. Therefore, the free space is also a continuous memory. (2) The Terminator is only a defense method. It can only ensure that the unmanaged resources allocated to a given type of objects are finally released. GC puts the objects to be terminated in a dedicated queue, and then asks another thread to execute the terminator of these objects. In this way, GC can continue to execute its current work and remove junk objects in the memory. In the next GC call, these terminated objects will be removed from the memory. As you can see, the object that needs to call the Terminator will stay in the memory for a GC cycle (the actual situation will be more complicated than this. For details, refer to the concept of "Generation" below ), therefore, we should try to minimize the use of the code logic to the Terminator. GC introduces the concept of "generation" (generation) to optimize execution. You can quickly find objects that are more likely to be spam. Since the last garbage collection, the newly created object belongs to The 0th generation object. If an object remains alive after a garbage collection, it will become a 1st-generation object. Objects that have not been destroyed after two or more garbage collections become 2nd-generation objects. In this way, local variables and objects used throughout the application life cycle can be treated separately. Most of the 0th s are local variables. The member variables and global variables will become 1st generation objects faster until 2nd generation. GC will optimize the execution process by reducing the number of times the 1st and 2nd generations of objects are checked. In each cycle, GC checks the 0th generation object. In general, in the GC of about 10 cycles, The 0th and 1st generation objects will be checked at the same time. In GC of about 100 cycles, all objects will be checked at the same time. We can see that an object to be summarized may stay at 9 GC cycles more than a common object. If the hype is still not completed during GC again, the object will continue to be upgraded to 2nd generations. For objects of the 2nd generation, a GC cycle of more than 100 times is often required to be cleared. To avoid this performance problem, we recommend that you use the IDisposable interface. (3) The Dispose () and Close () types that use non-system resources will automatically call Dispose () in the Terminator, so that the user can still ensure normal release of resources when they forget it, however, these resources will remain in the memory for a longer period of time, so the best solution is to use the Dispose () of the IDisposable interface as shown by the user. Dispose () does not remove an object from the memory, but instead releases the object from its unmanaged resources. Difference between Dispose () and Close () (Dispose () is better than Close () Close: clears resources, and the object does not need to be terminated, but GC is generally not called. suppressFinalize (), so the object is still in the end queue. Dispose: clears resources. Call GC. SuppressFinalize () to inform GC that the object no longer needs to be terminated. Use IDisposable. Dispose () to achieve standard destruction mode for destroying unmanaged resources.

 

(4) The usingusing statement ensures that the user's object can be destroyed normally in the simplest way, even if the object encounters an exception during the call operation. When multiple objects need to be destroyed, you can use multiple using blocks or one try/finally block. Using () {}= try {} finally {xxx. dispose ();} The following example ensures that the object is cleared correctly when obj is not null. When obj is null, using (null) does not report an error, however, no cleanup is performed. Object obj = Factory. createInstance (); using (obj as IDisposable) {Console. write (obj. toString ();} 8. operation sequence in which the first instance is created, to create the second and later instances of the same type, perform Step 9 from step 1 and compile the relevant information about the lifecycle:
  • C # efficient programming: 50 effective methods for improving C # code (version 2nd)

 

Author: B. it
Source: http://www.cnblogs.com/ImBit/p/5484920.html
The copyright of this article is shared by the author and the blog. You are welcome to repost this article, but you must keep this statement without the author's consent and provide a connection to the original article on the article page.

 

Related Article

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.