以下代码无法编译:
class Test<T> where T : class, IComparable
{
public bool IsGreater(T t1, T t2)
{
return t1 > t2; // Cannot apply operator '>' to operands of type 'T' and 'T'
}
}
我怎样才能让它发挥作用?我希望它适用于 T = int
、double
、DateTime
等。
最佳答案
IComparable
您在此处用作类型约束的接口(interface)为您提供了 CompareTo
方法。所以你可以这样做:
public bool IsGreater(T t1, T t2)
{
return t1.CompareTo(t2) > 0;
}
关于c# - 我如何比较相同泛型类型的两个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69899514/