Error 1 'Koordinates.Vieta' does not implement interface member '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);
}
}
请您参考如下方法:
您有一个采用 Vieta 实例的比较方法类(class)。 IComparable 接口(interface)声明了一个方法 CompareTo(object) (请注意,参数类型应为 object )。
拥有强类型的 CompareTo 方法当然更好。你可以实现 IComparable<T> 界面也是如此。
我的建议是这样做,并实现 IComparable显式接口(interface)。然后,你会得到这样的结果:
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显式接口(interface),CompareTo(object)方法将从智能感知中隐藏。事实上,如果将类转换为接口(interface)类型(或者如果将该类的实例传递给采用 IComparable 参数的方法,例如),您将只能调用该方法。
