使用泛型参数作为基类

时间:2018-05-15 04:46:34

标签: c# oop inheritance

我可以在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
}

0 个答案:

没有答案
相关问题