Read improving C # code 157 recommendations: Recommended 10~11

Source: Internet
Author: User

Directory:

    • Recommendation 10: Consider whether to implement a comparer when creating objects
    • Recommendation 11: discriminate between = = and equals

I. Recommendation 10: When creating an object, consider whether to implement the comparer

Compare base pay:

 classsalary:icomparable { Public stringName {Get;Set; }  Public decimalbasesalary {Get;Set; }
Public decimal Bonus {get; set;} Public intCompareTo (Objectobj) {Salary Comparer= obj asSalary; if(Basesalary >comparer. Basesalary) {return 1; } Else if(Basesalary = =comparer. Basesalary) {return 0; } Else { return-1; } } }

Client calls:

list<salary> salaries =NewList<salary>(); Salaries. ADD (NewSalary () {Name ="Sun", basesalary = + }); Salaries. ADD (NewSalary () {Name ="Yuan", basesalary = - }); Salaries. ADD (NewSalary () {Name ="Kun", basesalary = the }); Salaries. ADD (NewSalary () {Name ="Qun", basesalary = the }); Salaries. ADD (NewSalary () {Name ="Sun", basesalary =4000 }); Salaries.            Sort (); foreach(varSinchsalaries) {Console.WriteLine ("' Name ': {0}, ' basesalary ': ¥{1}{2}", S.name, s.basesalary,system.environment.newline); } console.readkey ();

Run:

If you do not want to sort with base pay basesalary, but instead use the bonus bonus to sort, implement a custom comparer using IComparer:

class Bonuscomparer:icomparer<salary>    {        publicint Compare (Salary sarlary y)        {           return  left.Bonus.CompareTo (right). Bonus);        }    }

The client provides the comparer we created above:

list<salary> salaries =NewList<salary>(); Salaries. ADD (NewSalary () {Name ="Sun", basesalary = +, bonus=4000 }); Salaries. ADD (NewSalary () {Name ="Yuan", basesalary = -, Bonus = the }); Salaries. ADD (NewSalary () {Name ="Kun", basesalary = the, Bonus = - }); Salaries. ADD (NewSalary () {Name ="Qun", basesalary = the, bonus=4000 }); Salaries. ADD (NewSalary () {Name ="Dun", basesalary =4000, bonus=0 }); Salaries. Sort (Newbonuscomparer ()); foreach(varSinchsalaries) {Console.WriteLine ("Name: "{0}", basesalary:¥{1},bonus:{2}{3}", S.name, S.basesalary,s.bonus, System.Environment.NewLine); } console.readkey ();

Output:

Ii. recommendation 11: discriminate between = = and equals

Both refer to equality, that is, value equality and reference equality.

Value type: Returns True if the value type is equal.

Reference type: Returns True if it points to the same reference.

Well understood, for example:

1. Value type: = = and Equls ()

intx =1; inty =1; Console.WriteLine ("int x=1; {0}int Y=1; {0}", System.environment.newline,system.environment.newline); Console.WriteLine ("x==y:{0}", x = =y); Console.WriteLine ("x.equals (y): {0}{1}", X.equals (y), System.Environment.NewLine); X=y; Console.WriteLine ("x=y; {0}", System.Environment.NewLine); Console.WriteLine ("x==y:{0}", x = =y); Console.WriteLine ("x.equals (y): {0}", X.equals (y)); Console.readkey ();

Run:

2. Reference type

class people    {        publicgetset;}    }

Client:

People p1 =NewPeople () {Name ="Sun" }; People P2=NewPeople () {Name ="Yuan" }; Console.WriteLine ("people p1 = new people (); {0} People p2 = new People (); {1}", System.Environment.NewLine, System.Environment.NewLine); Console.WriteLine ("p1==p2:{0}", p1 = =p2); Console.WriteLine ("P1. Equals (p2): {0}{1}", p1.            Equals (p2), System.Environment.NewLine); Console.WriteLine ("------------------------------------"); P1=P2; P1. Name="Moon"; Console.WriteLine ("P1=P2; {0}", System.Environment.NewLine); Console.WriteLine ("p1==p2:{0}", p1 = =p2); Console.WriteLine ("P1. Equals (p2): {0}", p1. Equals (p2));

Run:

later we modified the value of Name= "Moon" in P1, but the name value of P2 became Moon. the with, = = and equal () when comparing reference types, the reference address returns True

3, reference type overload equals () to achieve value type comparison effect

Also, sometimes we need our type to look like a string type, with a sense of value type. So, this reference type, we need to overload = = or Equals ().

It is recommended that only equals () be overloaded to achieve the same effect as the value type. Reserve = = To preserve reference comparisons. For example: In life we think the identity card number is the same person.

 class   people { public  String Name {get ; set          public  string  idcode {get ; set          public  override  bool  Equals (object   obj) {Peo            ple p  = obj as   people;         return  p.idcode == Idcode; }    }

Client:

People p1 =NewPeople () {idcode="No1" }; People P2=NewPeople () {Idcode ="No1" }; Console.WriteLine ("people p1 = new people (); {0} People p2 = new People (); {1}", System.Environment.NewLine, System.Environment.NewLine); Console.WriteLine ("P1. IDCODE={0}", p1.            Idcode); Console.WriteLine ("P2. IDCODE={0}", p2.            Idcode);            Console.WriteLine (); Console.WriteLine ("p1==p2:{0} "preserve reference address comparison"", p1 = =p2); Console.WriteLine ("P1. Equals (p2): {0} "overloaded compare Idcode, value type comparison effect" {1}", p1.            Equals (p2), System.Environment.NewLine); Console.WriteLine ("----------------------------------"); P1=P2; P1. Idcode="No2"; Console.foregroundcolor=consolecolor.red; Console.WriteLine ("P1. IDCODE={0}", p1.            Idcode); Console.WriteLine ("P2. IDCODE={0}", p2.            Idcode);            Console.WriteLine (); Console.foregroundcolor=Consolecolor.white; Console.WriteLine ("P1=P2; {0}", System.Environment.NewLine); Console.WriteLine ("p1==p2:{0}", p1 = =p2); Console.WriteLine ("P1. Equals (p2): {0}", p1.            Equals (p2)); Console.readkey ();

Run:

Also, the Object.referenceequals method compares the instances with the same. Validates the equality of the reference.

Read improving C # code 157 recommendations: Recommended 10~11

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.