157 suggestions for writing high-quality code to improve C # programs [10-12]

Source: Internet
Author: User

This article has been updated to http://www.cnblogs.com/aehyok/p/3624579.html. This article mainly records the following content:

10. When creating an object, consider whether to implement a comparator.

11. differential treatment = and Equals

12. We recommend that you rewrite GetHashCode when rewriting Equals.

When there are objects, there will be comparisons. Just like every time I take the examination paper back home when I was a child, my mother will ask you who is next door and who has scored more or less points. The following is a simple example of a Salary list of several people. We will list them based on the basic salary:

      Main(=  ( obj 

You can use the ArrayList. Sort () method to complete sorting tasks. However, ArrayList can only be a field. If there are two fields: Name and salary, and then sort by salary, then according to the current situation, ArrayList cannot be implemented. Therefore, the IComparable interface can be used now. Now, define an object and implement the IComparable interface.

                     Name { ;                     BaseSalary { ;                                       CompareTo(= obj  (BaseSalary >   (BaseSalary ==  -

Sort

                ArrayList array =  Salary() { Name = , BaseSalary =  Salary() { Name = , BaseSalary =  Salary() { Name = , BaseSalary =  Salary() { Name = , BaseSalary =  (Salary obj .Format(

If the Icomparable interface is not inherited. The following error occurs.

The result is as follows:

Assume that a bonus field is added to the Salary class as follows:

                     Name { ;                     BaseSalary { ;                     Bouns { ;                                       CompareTo(= obj  (BaseSalary >   (BaseSalary ==  -

What should I do if I want to sort it with the Bouns bonus field again? Of course, it is no problem to modify the interface methods inherited in the Salary object class for processing, but it is troublesome. We can use the custom comparison interface IComparer.

       Compare( x, = x = y 

Then sort again

                ArrayList array =  Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= (Salary obj .Format(

The result is as follows:

Note: The Implementation interface is called IComparable, And the custom comparator interface is IComparer.

If we have some experience, we will find problems in the following functions:

          Compare( x, = x = y 

This function performs transformation processing, which will affect the performance. If the set contains thousands of complex entity objects, it takes a lot of time to sort objects. This problem is well solved when the generic model is launched.

Therefore, the ArrayList in the above Code can be replaced with List <T>, so we should implement IComparable <T> and IComparer <T>.

The implementation code is as follows:

1. Object Class implementation interface IComparable <T> 2. Custom comparator implementation interface IComparer <T> 3. Call for sorting

      Salary:IComparable<Salary>                    Name { ;                     BaseSalary { ;                     Bouns { ;                                      
      BounsComparer : IComparer<Salary> 
                List<Salary> array = List<Salary> Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= Salary() { Name = , BaseSalary = ,Bouns= (Salary obj .Format(

Final Result

Here I have a blog post dedicated to = and Equals, here I will not elaborate too much on the http://www.cnblogs.com/aehyok/p/3505000.html

Let's take a look at a simple small example to define the following object classes:

       IDCode { ;  Person(.IDCode =   Equals( IDCode == (obj 

Compile the object class above

There will be a prompt to temporarily ignore

       SomeThing { ; 

Through these two entity classes, we use the following Dictionary type, the Code is as follows:

     Dictionary<Person, PersonMoreInfo> PersonValues =  Dictionary<Person, PersonMoreInfo>  Main(=  Person( =  Person(=  PersonMoreInfo() {  SomeThing=

           

Then run the above Code and you will find

The HashCode of the two is the same, and the dictionary will also find the corresponding key value.

The GetHasCode method has another problem, that is, it always returns only one integer, while the capacity of the integer type obviously cannot meet the capacity of the string.

             str1 =  str2 = 

The two strings generate the same HasCode. To reduce this situation, we will make a slight modification:

           (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName++

While rewriting the Equals method, you should also implement a type-safe interface IEquatable <T>, so the final Code of the Person type is as follows:

      Person:IEquatable<Person>  IDCode { ;  Person(.IDCode =   Equals( IDCode == (obj    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName++  IDCode ==

The IEquatable API has not been used for the moment. First use.

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.