Pocket Notes (i): C # Programming Essentials

Source: Internet
Author: User
Tags finally block

Preface

The Pocket Note series focuses on recording everyday small technical points, although there may be little connection between points and points. But small enough, it is also easy to familiarize and apply to the daily development cycle, resulting in practical benefits. Remember is the first step, not the ultimate goal. The ultimate goal is to develop high-efficiency programs that take into account flexibility, scalability, and portability under the understanding principle. This series begins with a small knowledge of C #, but is not limited to a specific language. From the hands of daily extracts of the information and books, is a summary of what has been seen, some notes have read experience, there are some only outline or conclusions. (Note: Most of the points in this article require practical development experience to help read comprehension.) )

Catalogue
    • Const and READONLY
    • IS, as
    • Conditional Compilation # if #endif和Conditional特性
    • Equivalence judgment
    • GetHashCode () traps
    • Commissioned
    • Resource management (GC, finalizer, IDisposable, using)
    • Sequence of operations to create the first instance
    • The life cycle of the compilation
I. CONST and READONLY

When the compile-time constant const is compiled into IL, it is replaced with the literal value represented. So changing the value of a public compile-time constant requires recompiling all code referencing that constant to ensure that all code uses the most recent constant value.

Conversely, the run-time constant is compiled into IL by referring to the variable of readonly, not the value of the variable, but simply recompiling the code that changed the constant value, enabling compatibility with other published code at the binary level.  second, is, as

In two cases:

the target type of the conversion is the reference type: The is test can be successfully converted and then converted with AS (as null when the conversion object is null). As and is does not perform a user-defined conversion, only if the run-time type is a target type or a derived type of the target, the conversion succeeds. Performing a user-defined conversion can be done with casts. the target type of the conversion is a value type: You cannot use as, you can use casts.  third, conditional compilation # if #endif和Conditional特性both are suitable for daily commissioning. #if can be interspersed with conditional code in a function, but using the conditional attribute can restrict the separation of conditional code (such as debug) at the function level, guaranteeing a good structure of the code.  Iv. equivalence judgment(1) several key points of equivalence in mathematics:reflexive (reflexive): Indicates that any object is equal to itself, no matter what type A is, a==a should return true;symmetry (symmetric): means that the order of the equivalence judgment is insignificant, and if A==b returns True, then B==a must also return true;transitive (transitive): The meaning is that if a==b and b==c all return true, then A==c must also return true;value equal (corresponds to value type): "Value is equal" if the variable type of the two value types is the same and contains the same content;reference Equality (corresponds to reference type): "Reference equals" if the variables of the two reference types point to the same object;(2) Four methods of equality judgment in C #Public static bool ReferenceEquals (object Left,object right)regardless of whether a value type or reference type is being compared, the method is judged by the object identifier. So to compare two value types, the result is always false, the reason is boxing. When creating your own classes, there is little need to overwrite them. Public static bool Equals (object Left,object right)This method is used when you do not know the run-time type of two variables. The internal implementation of the first reference referenceequals to judge, and then take left and right and null to judge, and finally use left. Equals (right) to judge. When creating your own classes, there is little need to overwrite them. Public virtual bool Equals (Objcet rigth)There are two types of situations:for reference type System.Object: Use the object identity as a judge of whether two objects are "reference equal" and the default implementation is exactly the same as referenceequals. You do not need to overwrite a new reference type. for value type System.ValueType: Override this method in System.Object to determine whether "value is equal". Because it is not possible to know the current specific value type, reflection is used and the efficiency is low. It is recommended that you overwrite the method when you create a new value type, and overwrite the GetHashCode () method. Public static bool operator== (MyClass Left,myclass right)Reference type System.Object: Use object identity as a judgment. value type System.ValueType: Override this method in System.Object because it is not possible to know the current specific value type, so the reflection is used less efficiently. It is recommended that you overwrite the method when you create a new value type, and overwrite the GetHashCode () method.  v. GetHashCode () TrapsIn reference type (System.Object): GetHashCode () works correctly, although it does not necessarily produce an efficient distribution. In value type (System.ValueType): Only if the first field of a struct is read-only, GetHashCode () works correctly, and GetHashCode () produces a more efficient hash code only if the first field contains a relatively random distribution of values. GetHashCode Overwrite rules
    1. If two objects are equal (judged by operator==), they must generate the same hash code. Otherwise, such a hash code will not be used to find objects in the container. System.Object: satisfies this rule; System.ValueType: Not all attributes that participate in the equivalence judgment are used for hash code calculations, but instead return the hash code for the first field defined in the struct type as a hash of the current value type, so it is assumed that the hash code equivalent of the equality judgment is definitely equal (in turn, the hash code is equal to same-sex judgment not necessarily equal). Satisfy this rule.
    2. for any object A,a.gethashcode () must remain unchanged. A.gethashcode () must always return the same value, no matter what method is raised on a. This ensures that the objects placed in the "bucket" are always in the correct "bucket". System.Object: satisfies this rule; the first field in System.ValueType:struct is a constant field that does not change over the lifetime (called an immutable value type) to satisfy this rule.
    3. New reference type is recommended to overwrite GetHashCode () System.ValueType: Depending on how the first field is used, if any value is taken, GetHashCode () can produce a fairly uniform distribution, but if you take the same value, there is no rule for this to be met.
  Vi. Commissionbuilt-in delegate form
    • Predicate<t>: Represents a function that provides a Boolean return value;
    • Action<t1,t2>: Accepts parameters of arbitrary parameters;
    • Func<t1,t2,resultt>: accepts 0 to multiple parameters and returns a single result;
. NET is a multicast delegate (multicast delegate), the multicast delegate will combine all the target functions added to the delegate into a single invocation. There are two points to note:
    1. During multicast delegate invocation, each target function is called sequentially. The delegate object itself does not catch an exception. Therefore, any exception thrown by the target ends the invocation of the delegate chain, which is not guaranteed to be secure if there is an exception to the delegate invocation.
    2. The return value of the entire call will be the return value of the last function call, and the return value of the preceding function will be ignored;
Workaround: Iterate through the invocation list and invoke each target function on the delegate chain delegate applied to callbacksmethods that accept predicate<>, action<>, func<> as parameters, such as List<t>. Find (predicate<t> p); sometimes when a lambda expression is passed in, the compiler converts the lambda expression into a method, creates a delegate, points to the method, and then invokes the delegate to implement the callback. delegate applied to event

. NET event pattern is the Observer pattern
public event eventhandler<loggereventargs> Log;
The compiler will automatically create code like the following, which you can write yourself as needed
Private eventhander<loggereventargs> log;
Public event eventhander<loggereventargs> Log
{
Add{log=log+value;}
Remove{log=log-value;}
}
Events are equivalent to a collection of delegates, which can add multiple delegates of the same type (via + =);

delegates can add multiple methods of the same type (via constructors or + =); VII. Resource Managementthe memory on the managed heap is managed by GC (garbage Collector garbage collector, the CLR contains GC), and other resources are the responsibility of the developer. . NET provides two mechanisms for managing the life cycle of unmanaged resources: finalizers (finalizer, called by the GC, calls occur at some time after the object becomes garbage, time is unpredictable), and the IDisposable interface. (1) GCThe GC is able to determine whether an entity is still referenced by the active object of the application, and for entities that are not directly or indirectly referenced by the active object, the GC will judge it as garbage. The GC compresses the managed heap each time it runs, compressing the managed heap to keep the objects that are still in use in contiguous memory, so the free space is a contiguous memory. (2) Terminatora finalizer is only a defense, which guarantees that the unmanaged resources allocated by a given type of object are eventually freed. The GC places the object that needs to be executed in a dedicated queue, and then lets another thread execute the finalizer of those objects. In this way, the GC can continue to perform its current work, remove the garbage object in memory, and remove those objects from memory that have been terminated in the next GC call. As you can see, the object that needs to invoke the finalizer will stay in memory for more than one GC cycle (this is a bit more complicated than this, see the concept of "generation" below for details), so you should minimize the logic of the code to use to finalizers. in order to optimize execution, the GC introduces the concept of "generation" (generation). You can quickly find objects that are more likely to be garbage. The newly created object belongs to the No. 0 generation object since the last garbage collection. If an object survives after a garbage collection, it becomes the 1th generation object. Objects that were not destroyed after two and two garbage collection became the 2nd generation object. This allows the local variables to be treated separately from the objects that have been used in the application life cycle. The No. 0 generation mostly belongs to local variables. member variables and global variables become 1th-generation objects faster, up to the 2nd generation. The GC optimizes the execution by reducing the number of times the 1th and 2nd generation objects are checked. In each cycle, the GC examines the No. 0 generation of objects. In general, about 10 cycles of GC, there will be one time to check both No. 0 and 1th generation objects. In a GC of about 100 cycles, all objects are checked at once. You can see that an object that needs to be summarized may stay 9 GC cycles longer than normal objects. And if the GC still does not complete the end of the hype, then the object will continue to be promoted to the 2nd generation. For the 2nd generation of objects, it often takes more than 100 GC cycles before the opportunity is cleared. To avoid this performance problem, we recommend that you use the IDisposable interface. (3) Dispose () and close ()types that use non-system resources automatically call Dispose () in the finalizer, so that resources are guaranteed to be freed normally when the user forgets, but these resources stay in memory for a longer period of time. So the best solution is to be freed by the user's own display of Dispose () using the IDisposable interface. Dispose () does not remove an object from memory, but simply frees the object from its unmanaged resources. the difference between Dispose () and close () (Dispose () is better than Close ())Close: Cleans up resources, objects no longer need to be terminated, but generally does not call gc.suppressfinalize (), so objects are still in the finalization queue. Dispose: Cleans up resources, calls Gc.suppressfinalize () tells the GC that the object no longer needs to be terminateduse IDisposable.Dispose () to implement standard destruction mode for destroying unmanaged resources
    1. Release all unmanaged resources;
    2. Releases all managed resources, including the release event listener;
    3. Sets a status ID that indicates that the object has been destroyed. If the public method of the object is re-used after the destruction, then the objectdisposed exception should be thrown;
    4. Call Gc.suppressfinalize (this) to skip the end operation;

(4) usingThe using statement is the simplest way to ensure that a user's object can be destroyed normally, even if the object has an exception when invoking an operation. When there are multiple objects that need to be destroyed, you can use multiple using blocks or one try/finally block. using () {}=try{}finally{xxx. Dispose ();}The following example guarantees that when obj is not NULL, the object is properly cleaned up, and when obj is null, using (NULL) does not give an error, but does not do any cleanup work. object Obj=factory.createinstance ();using (obj as IDisposable){Console.Write (obj. ToString ());}  Viii. sequence of operations for creating the first instanceThe order in which the first instance of a type is created, and the second and subsequent instances of the same type are created starting from step 5th
    1. The static variable is set to 0;
    2. Executes the static variable initializer;
    3. Executes the static constructor of the base class;
    4. Execute static constructors;
    5. The instance variable is set to 0;
    6. Executes the instance variable initializer;
    7. Executes the appropriate instance constructor in the base class;
    8. Executes the instance constructor;
 Nine, the life cycle of the compilation  Related information:
    • "C # Efficient Programming: 50 proven ways to improve C # code" (2nd edition)

b.it
Source: http://www.cnblogs.com/ImBit/p/5484920.html
This article is copyrighted by the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link.

 

Pocket Notes (i): C # Programming Essentials

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.