不实现System.IComparable.CompareTo(object)

时间:2012-11-21 21:51:24

标签: c# .net compiler-errors

  

错误1'Koordinates.Vieta'没有实现接口成员'System.IComparable.CompareTo(object)'

代码:

    public class Vieta : IComparable //error is thrown here, on "Vieta"
{
    public double x, y; 
    //constructor
    public Vieta(double a, double b)
    {
        x = a; y = b;
    }
    //read only parameter
    public double ilgis
    {
        get
        {
            return Math.Sqrt(x * x + y * y);
        }
    }

    public int CompareTo(Vieta other)
    {
        if (other == null) return 1;
        return other.ilgis.CompareTo(this.ilgis);
    }
}

2 个答案:

答案 0 :(得分:2)

您有一个比较方法,它接受Vieta类的实例。 IComparable接口声明方法CompareTo(object)(请注意,参数应为object类型。)

使用强类型的CompareTo方法更好。您也可以实现IComparable<T>接口。

我的建议是这样做,并明确地实现IComparable接口。然后,你最终得到这样的东西:

public class Vieta : IComparable, IComparable<Vieta>
{

    IComparable.CompareTo( object obj )
    {

       var other = obj as Vieta;

       if( other == null ) return false;

       return CompareTo(other);

    }


    public int CompareTo( Vieta other )
    {
         // Implement your compare logic here.
    }

}

通过显式实现IComparable接口,CompareTo(object)方法将从智能感知中隐藏。实际上,如果将类强制转换为接口类型(或者将该类的实例传递给采用IComparable参数的方法),则只能调用该方法。 / p>

答案 1 :(得分:2)

将课程更改为:

public class Vieta : IComparable<Vieta>

IComparable定义了int CompareTo(object),而通用IComparable<T>定义了int CompareTo(T)