Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IComparable实现-比较运算符重载_C# - Fatal编程技术网

C# IComparable实现-比较运算符重载

C# IComparable实现-比较运算符重载,c#,C#,我正在研究上面提到的,发生了一些有趣的事情。要重载比较运算符我必须从IComparable界面实现CompareTo方法。此方法采用类型为object的一个参数,但在我使用的书中的示例中,它使用自定义点类型编写方法,如下所示: public int CompareTo(Point other) { if (this.X > other.X && this.Y > other.Y) return 1; if (this.X < ot

我正在研究上面提到的,发生了一些有趣的事情。要重载比较运算符
我必须从
IComparable
界面实现
CompareTo
方法。此方法采用类型为
object
的一个参数,但在我使用的书中的示例中,它使用自定义
类型编写方法,如下所示:

public int CompareTo(Point other) {
    if (this.X > other.X && this.Y > other.Y)
        return 1;
    if (this.X < other.X && this.Y < other.Y)
        return -1;
    else
        return 0;
}
public int CompareTo(object obj) {
    Point other = (Point)obj;
    if (this.X > other.X && this.Y > other.Y)
        return 1;
    if (this.X < other.X && this.Y < other.Y)
        return -1;
    else
        return 0;
}

这本书没有提到这方面的任何内容。我的问题是:为了让一个接口被认为是由编译器实现的,这个强制转换是否总是必要的?或者是更“直接”的方法吗?

您有两个版本的
i可比较的
。泛型和非泛型。两者都位于
系统
命名空间下。当您实现非泛型的
IComparable
版本时,您需要在您的类型上提供的方法是:

int CompareTo(object obj)
代替通用
i可比较
版本的签名:

int CompareTo(T obj)
因此,在非泛型的
IComparable
中,您需要强制转换此
obj
,因为它被装箱到
对象中。为确保通过正确的类型,您可以尝试使用safecast,例如:

if (obj == null)
   throw new ArgumentNullException("The obj must be provided");

var anotherCustomer = obj as Customer;
if (anotherCustomer == null)
   throw new ArgumentException("The obj must be a Customer");

另一方面,您有通用版本,适用于需要特定类型的情况。

有两种类型的
i可比较
通用和非通用,这取决于您实现的类型,然后需要不同的参数。如果(obj==null)返回1,则添加
在非通用版本中。Valeu pela resposta Felipe!;)