C # study notes 7,

Source: Internet
Author: User

C # study notes 7,

1.Note the following when rewriting the GetHashCode method:

(1) override the GetHashCode method and the Equals method. Otherwise, the compiler will warn.

(2) The same object must have an equal hash code (if a. Equals (B), a. GetHashCode () = B. GetHashCode ()).

(3) GetHashCode () should not cause any exceptions. GetHashCode () must always return a successful value.

(4) hash codes should be unique as much as possible.

(5) The performance of GetHashCode () should be optimized. GetHashCode () is usually used in Equals () implementation for a complete equality comparison (if the hash code is different, of course there is no need to make a complete equality comparison), so when the type is used as the key type in the dictionary set, this method is frequently called.

(6) for a specific object, during the lifetime of the object, GetHashCode () should always return the same value, even if the object data has changed. In many cases, the return value of the method should be cached to ensure this.

Other: we usually adopt the XOR (exclusive or) Operator for hash codes of the corresponding type, and ensure that the operands of XOR are not similar or equal. Otherwise, the result will be all zero. When the operands are similar or equal, consider using shift and addition operations. Other alternative operators -- and or -- have similar restrictions. These restrictions occur more frequently AND are gradually changed to 0 when they are used multiple times; multiple applications OR applications will gradually become 1. For more detailed control, you should use the shift operator to break down a type larger than int. For example, if there is a long type named value, its GetHashCode () method can be implemented as follows: int GetHashCode () {return (int) value ^ (int) (value> 32 )}.

2.In an object, the implementation of the virtual method Equals () is to judge equality using ReferenceEquals. This implementation is often inadequate, so it is generally necessary to override the Equals () method.

3.Note the following when rewriting the Equals () method ,:

(1) check whether it is null;

(2) if it is a reference type, check whether the reference is equal;

(3) check whether the hash code is equal. If the hash code is not equal, it is not necessary to continue a comprehensive, field-by-field comparison. (Two identical objects cannot have different hash codes)

(4) compare each Identification field to determine whether it is equal.

4.Guiding principles for Equality Implementation:

(1) Equals (), =, and! = Operators should be implemented together;

(2) One type is in Equals (), =, and! = The same algorithm should be used in implementation;

(3) Implement Equals (), =, and! =, A type of GetHashCode () method should also be implemented;

(4) GetHashCode (), Equals (), =, and! = An exception is never thrown;

(5) When implementing IComparable, methods related to equality should also be implemented;

You can view the definition of the Coordinate class for easy and intuitive understanding.

5.Definition of other binary operators (such as "+,-, &"): Just like the definition of "=, at least one parameter is of the current type (the type of the currently overloaded operator ). After redefining these binary operators, you can perform operations just like the basic numeric type. You can view the Coordinate class.

6.Other unary operators (such as "+ positive,-negative ,! , True, false) is similar to the heavy-load binary operator, but the heavy-load "true, false" must appear in pairs, the heavy-load parameter is changed to. The "true" and "false" operators are mainly used with control expressions such as if, do... while, and.

7.Transformation operators: Transition operators are divided into explicit and implicit (implicit). implicit transformation is always successful, and explicit transformation reminds users that this is unwanted behavior, there are two explicit problems: "① conversion may be abnormal, ② conversion may have some data loss ". You can view the sample code of the Angle structure.

8.Namespace: The namespace can be nested, that is, the class can be nested. There are two types of namespace nesting, namely, the Declaration hierarchy nesting. When declaring, the "." symbol is separated. For example, System. IO.

9.Xml document that generates comments to class files: You can use the "csc/doc: Document name. xml class file" command tool in ". In fact, you can also in the VS-IDE project properties => Generate => set xml document output, you can generate project documentation instructions, of course, you can use some free tools for document generation (such as GhostDoc, NDoc ). When the Assembly is provided to others for use (the Assembly does not contain instructions, and the compiler ignores the comments in the source code), to enable VS intelliisense to prompt the member description information in the Assembly, make sure that the file name of the XML file is the same as that of the Assembly that you want to support. Make sure that the XML file and the Assembly are in the same directory so that you can refer to the Assembly in the Visual Studio project. xml file.

10.Terminator: A Terminator is used to clear expensive resources (such as database connections and file handles) occupied by a class. It cannot be explicitly called and is called by the garbage collector, therefore, we cannot determine the time when the Terminator is executed during compilation. The only difference is that the Terminator will run at a certain time before the object is used and the application is closed. The declaration method is "~ Class Name () {} ", parameter passing and adding such as public modifier are not allowed, because it cannot be explicitly called. The Terminator in the base class is automatically called as part of the final call of the object. You can view the processing code of the TemporaryFileStream class.

11.Using statements for deterministic termination: the problem with the terminator itself is that they do not support a deterministic termination (that is, the ability to predict the running time of a terminator). On the contrary, the Terminator is used as a backup mechanism for resource cleaning. If developers forget to explicitly call the necessary cleanup code, they can rely on the terminator to clean up resources. To determine the termination, the class must implement the IDisposable interface, which contains the Dispose () method. You must implement the specific details to clear the resources. Using the using statement to end and using try-finally for processing is an effect, because the using statement here is the try-finally statement in the final generated pencil code, the using statement only provides a syntax shortcut for the try-fianlly block. Multiple variables of the same type can be instantiated in using to process the release together. You can view the processing code of the TemporaryFileStream class.

12.Guiding principles for resource utilization and termination:

(1) finalize is implemented for an object only when the object uses scarce or expensive resources, and the end will delay garbage collection.

(2) objects with Terminators should implement the IDisposable interface to support deterministic termination.

(3) The termination method usually calls the same code as the IDisposable call.

(4) The Terminator should avoid any unhandled exceptions.

(5) deterministic termination methods such as Dispose () and Close () should call GC. SuppressFinalize () to make garbage collection faster.

(6) The resource cleanup method should be simple enough and should focus only on the reason for terminating the resources referenced by the instance.

(7) If the base class implements Dispose (), the implementation of the derived implementation should call the implementation of the base class.

13.Delayed initialization Lazy <T>: In. net4.0 provides Lazy <T> to initialize the object with a delay (that is, it is created only when the object is required). You can view the implementation of the DataCache class.

 

Public class Coordinate {// <summary> // Longitude // </summary> public Angle longpolling {get; set ;} /// <summary> /// dimension // </summary> public Angle Latitude {get; set;} public override int GetHashCode () {int hashCode = longpolling. getHashCode (); if (hashCode! = Latitude. getHashCode () {hashCode ^ = Latitude. getHashCode () ;}return hashCode;} public override bool Equals (object obj) {if (obj = null) {return false;} return Equals (Coordinate) obj );} public bool Equals (Coordinate obj) {if (obj = null) {return false;} if (GetHashCode ()! = Obj. getHashCode () {return false;} return longpolling. equals (obj. longpolling) & Latitude. equals (obj. latitude);} public static bool operator = (Coordinate one, Coordinate two) {if (ReferenceEquals (one, null) // null is not used here =, it is because we have redefined the "=" operator of this class, otherwise it will enter recursion and cause an endless loop. {Return ReferenceEquals (two, null);} return one. Equals (two);} public static bool operator! = (Coordinate one, Coordinate two) {return! (One = two);} public static Coordinate operator + (Coordinate one, Coordinate two) {return new Coordinate () {longpolling = one. longpolling + two. longpolling, Latitude = one. latitude + two. latitude };} public static bool operator! (Coordinate one) {return false;} public static bool operator true (Coordinate one) {return one. latitude. hours> 0 & one. latitude. minutes> 0 & one. latitude. seconds> 0;} public static bool operator false (Coordinate one) {if (one) {return false;} return true ;}} public struct Angle {public Angle (int hours, int minutes, int seconds) {Hours = hours; Minutes = minutes; Seconds = seconds;} publ Ic int Hours {get; set;} public int Minutes {get; set;} public int Seconds {get; set;} public Angle Move (int hours, int minutes, int seconds) {return new Angle (Hours + hours, Minutes + minutes, Seconds + seconds);} public override int GetHashCode () {return base. getHashCode ();} public override bool Equals (object obj) {return Equals (Angle) obj);} public bool Equals (Angle obj) {return Ho Urs = obj. hours & Minutes = obj. minutes & Seconds = obj. seconds;} public static Angle operator + (Angle one, Angle two) {return one. move (two. hours, two. minutes, two. seconds);} public static implicit operator string (Angle one) {return string. format ("{0}, {1}, {2}", one. hours, one. minutes, one. seconds);} public static explicit operator Angle (string text) {try {var result = text. split (','). C Ast <int> (); return new Angle (result. elementAt (0), result. elementAt (1), result. elementAt (2);} catch (Exception ex) {throw ex ;}} public class TemporaryFileStream: IDisposable {public TemporaryFileStream (string fileName) {// todo }~ TemporaryFileStream () {Dispose ();} private readonly FileStream _ stream; public FileStream Stream {get {return _ stream;} private readonly FileInfo _ file; public FileInfo File {get {return _ file;} public void Dispose () {Stream ?. Close (); File ?. Delete ();/* this statement is used to remove the TemporaryFileStream class instance from the final queue. An object in the final queue will not be garbage collected. It must be terminated before garbage collection, executing this statement will not delay the garbage collection of the object. */GC. suppressFinalize (this) ;}} public class DataCache {public DataCache () {_ fileStream = new Lazy <TemporaryFileStream> () => new TemporaryFileStream (FileStreamName ));} public string FileStreamName {get; set;} private Lazy <TemporaryFileStream> _ fileStream; public TemporaryFileStream FileStream {// "value" is executed only when "()" is returned. => new TemporaryFileStream (FileStreamName) "code, get {return _ fileStream. value ;}}/*. private TemporaryFileStream _ fileStream; public TemporaryFileStream FileStream {get {if (_ fileStream = null) {_ fileStream = new TemporaryFileStream (FileStreamName );} return _ fileStream ;}}*/}

 

------------------------ The above content is organized according to the "C # the third edition of the essence theory ".

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.