首页 > 解决方案 > 在哪里可以找到 IComparable 的 CompareTo 方法定义?

问题描述

在哪里可以找到 CompareTo 方法定义?

作为下面的代码,我可以通过实现 IComparable 接口来使用 CompareTo 方法。但是我没有在我的 Utilities 类中给出 CompareTo 方法的任何定义。我知道这是一个非常微不足道的问题。但我不明白一个类如何在不提供方法实现的情况下实现接口。

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

标签: c#oop

解决方案


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.


推荐阅读