我可以在C#
class A<TBase> : TBase {}
这就是我要粗略地做的事情:
public class Comparable<T, TBase> : TBase, IComparable<T>
{
public abstract int CompareTo(T other);
public static bool CompareTo(T x, T y) {
return x != null ? x.CompareTo(y) : (y != null ? 1 : 0);
}
public static bool operator<(T x, T y) {
return CompareTo(x, y) < 0;
}
public static bool operator<=(T x, T y) {
return CompareTo(x, y) <= 0;
}
public static bool operator>(T x, T y) {
return CompareTo(x, y) > 0;
}
public static bool operator>=(T x, T y) {
return CompareTo(x, y) >= 0;
}
public static bool operator==(T x, T y) {
return CompareTo(x, y) == 0;
}
public static bool operator!=(T x, T y) {
return CompareTo(x, y) != 0;
}
}
对评论的回复,以及我试图避免的重复代码的一些示例:
class Height {
// This needs to be a class not an int because we want to forbid
// silly things like multiplying heights
private int _heightInMillimeters;
// Lots of comparison operators here:
// ...
}
class Weight {
// This needs to be a class not an int because we want to forbid
// silly things like multiplying weights by heights etc
private double _weightInKilograms;
// Lots of comparison operators here:
// ...
}
class SomeOtherClassThatIdLikeToCompare {
// More boilerplate comparison operators here
}