C # icomparable interface, icomparer interface, compareto (Object X) method, and compare () method

Source: Internet
Author: User
Tags comparable

String comparison is often used in projects, but sometimes there are many string operations and different rules. For example, in some cases, we need to use sorting rules, and in some cases case-insensitive. How can we write a comparison method that is easier to operate? Implementing the icomparer interface is a good solution.

 

Icomparable. compareto Method

On msdn, This is the explanation (machine translation:

Icomparable interface:Defines a type-specific general comparison method. value types or classes are sorted by this method.

Icomparer interface:Publish a method to compare two objects.

 

Detailed understanding is:

By default, the equals (Object O) method of the object (provided by the Base Class Object) is used to compare whether two object variables reference the same object.

We must define our own object and the object comparison method.

The icomparable and icompare interfaces are the standard methods for comparing objects in. NET Framework. The differences between these two interfaces are as follows:

Icomparable can compare this object with another object. Generally, we use icomparable to provide the default comparison code of the class, and use other classes to provide non-default comparison code. The Chinese name should be "comparable objects ".

Icomparer is implemented in a separate class. It means that the current object can be used to compare any two objects, and the current object itself is not involved in computing. The Chinese character should be called a "Comparator ".

Compareto: icomparable provides the int compareto (Object OBJ) method ). This method accepts an object, compares the object of the current instance with another object of the same type, and returns an integer, this integer indicates whether the current instance is located before, after, or in the same order as another object.

Compare: icomparer also provides the compare () method. This method accepts two objects and returns an integer result, which is the same as compareto.

 

Icomparable Interface

For example, a default Instance Object person1 needs to be determined with person2 to determine whether person1 is older or younger than person2. in fact, this method returns an int, so the following code shows that person1 is older or younger.

1 If (person1.compareto (person2) = 0) 2 2 {3 3 console. writeline ("Same Age"); // same age, returns 0 4 4} 5 5 else if (person1.compareto (person2)> 0 after comparing person1 and person2) 6 6 {7 7 console. writeline ("person1 is older"); // If person1> person2, person1 and person2 are compared, a positive integer is returned, person1 is older than person2 8} 9 9 else10 10 {11 11 console. writeline ("person1 is younger"); // if the above-mentioned if is not true, a positive integer is returned after comparing person1 <person2, person1 and person2. person1 is 12 years younger than person2}

 

Icomparer Interface 

Use person as an example.

For example, if there is an object person1 that needs to be determined with person2 to determine whether person1 is older or younger than person2. in fact, this method also returns an int, however, we use compare of another interface (icomparer), so we can use the following code to explain whether person1 is older or younger.

 1 if(personComparer.Compare(person1,person2) == 0) 2 { 3   Console.WriteLine("same age"); 4 } 5 else if(personComparer.Compare(person1,person2) > 0 ) 6 { 7   Console.WriteLine("person 1 is older"); 8 } 9 else10 {11   Console.WriteLine("person1 is younger");12 }

In both cases, the parameters (person1 and person2) provided to the method are of the system. Object type. That is to say, two objects of any type can be compared. Therefore, some types of comparison are usually required before the returned results. If an error type is used, an exception is thrown. In fact, we use the generic interface icomparable <t> to omit object conversion.

The size comparison between objects is still used in the development process. For example, string is a comparable object and can be compared with another string, it will be compared in alphabetical order. However, sometimes some of our logic requires some special comparison methods. For example, the file sequence in windowsexplorer is regarded as "file10.txt"> "file2.txt ". At this time, we need to write a special icomparer object to implement these specific logics.

 

Split line -----------------------------------------------------------------------------

 

Comparison of icomparable. compareto (Object X:

The return value of compareto () is an integer type. It compares the size of the corresponding character (ASCII order) first. If the first character is different from the first character of another parameter, the comparison ends, returns the difference between their ASCII codes. If the first character is the same as the first character of another parameter

The character is compared with the second character of another parameter, and so on until the comparison of the character or the character to be compared is complete, then the length of the character is compared.

Java example:

String S1 = "ABC ";
String S2 = "ABCD ";
String S3 = "abcdefg ";
String S4 = "1 bcdfg ";
String S5 = "cdfg ";
System. Out. println (s1.compareto (S2); //-1 (equal front, 1 smaller S1 length)
System. Out. println (s1.compareto (S3); //-4 (equal front, small S1 length 4)
System. Out. println (s1.compareto (S4); // 48 (the ASCII code of "a" is 97, and the ASCII code of "1" is 49, so 48 is returned)
System. Out. println (s1.compareto (S5); //-2 (the ASCII code of "a" is 97, and the ASCII code of "C" is 99, So-2 is returned)

Split line -----------------------------------------------------------------------------

C # How to Implement the compareto () method

When can I use the icomparable. compareto (Object OBJ) method?

If a class implements the icomparable interface, you can override the compareto (Object OBJ) method in the icomparable interface. If there are several student objects in the Set, they must be sorted by the Student name, you can rewrite the compareto method to sort by name, but what if you want to sort by age? The compareto method can only be rewritten once. In this case, you can use icompare. Icompare is called a comparator. The default sort () sorting method of the set has an overloaded parameter that is the icompare comparator object.

Like all collection classes, it allows you to sort all objects that implement the icomparable interface. In the next example, you will modify the namecompare class to implement the icomparable generic interface:

Public class namecompare: icomparable <student>

To implement the icomparable <student> interface, the namecompare object must provide the compareto () method:

1 class namecompare: icomparer <student> // name ascending order 2 {3 Public int compare (student X, student y) 4 {5 return X. name. compareto (Y. name); 6} 7} 8 9 class namecompare1: icomparer <student> // name descending order 10 {11 Public int compare (student X, student y) 12 {13 return y. name. compareto (X. name); 14} 15} 16 17 class agecompare: icomparer <student> 18 {19 public int compare (student X, student y) 20 {21 return X. age. compareto (Y. age); 22} 23}

To sort:

Private void button3_click (Object sender, eventargs e) {Init (); students. sort (New namecompare (); // name in ascending order. The parameter of the sort method is the object of the class that implements the icompare interface show (students);} private void button4_click (Object sender, eventargs e) {Init (); students. sort (New namecompare1 (); // show (students) in descending order;} private void button5_click (Object sender, eventargs e) {Init (); students. sort (New agecompare (); show (students );}

 

Forward instructions Source: http://www.cnblogs.com/abc1069/p/3993818.html

C # icomparable interface, icomparer interface, compareto (Object X) method, and compare () method

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.