如何比较相同泛型类型的两个值?

use*_*521 2 c#

以下代码将无法编译:

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'
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它发挥作用?我希望它适用于 T = intdoubleDateTime等。

Dav*_*idG 8

IComparable您在此处用作类型约束的接口为您提供了一个方法CompareTo。所以你可以这样做:

public bool IsGreater(T t1, T t2)
{
    return t1.CompareTo(t2) > 0;
}
Run Code Online (Sandbox Code Playgroud)