简体   繁体   中英

Where can I find the IComparable's CompareTo method definition?

Where can I find the CompareTo method definition?

As the Below code, I can get the use of CompareTo method by implementing IComparable interface. But I haven't given any definition for the CompareTo method in my Utilities class. I know this is a very trivial question to ask. But I don't understand how a Class implements an interface without giving its method implementation.

public class Utilities<T> where T : IComparable
    {
        public T Max(T a, T b)  
        {
            return a.CompareTo(b) > 0 ? a : b;
        }
    }

Your Utilities class is not implementing IComparable . You are saying that T must implement IComparable . If Utilities were to implement IComparable , it would look like this:

public class Utilities<T> : IComparable

You don't need to define a CompareTo method in Utilities because that should be defined in T , whatever T is.

For example, you can't use Foo for T because Foo does not implement IComparable :

class Foo { 
   // you must add a CompareTo method here in order to use Foo as T
   // you must also add ": IComparable"
}

But you can use string or int or float because they do implement IComparable .

You are using generic type constraint rather than implement IComparable interface, Which means T must implement from IComparable .

If you want to implement IComparable interface you need to use : after class name and before where constraint keyword.

public class Utilities<T> : IComparable 
    where T : IComparable

{
    public int CompareTo(object obj)
    {

    }

    public T Max(T a, T b)
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM