是什么决定了我是否可以使用比较运算符?

What determines whether I can use the comparison operators?

我写了一个通用的扩展方法来查看一个Key是否在某个范围内:

public static bool IsInRange(this Key key, Key lowerBoundKey, Key upperBoundKey )
{
    return lowerBoundKey <= key && key <= upperBoundKey;
}

这看起来很简单,但假设我想编写一个等效的通用方法,它适用于任何可以使用 <= 比较运算符的类型:

public static bool IsInRange(this T value, T lowerBound, T upperBound )
{
    return lowerBound <= value && value <= upperBound;
}

如何应用 where T : ISomethingIDontKnow 才能进行编译?

使用 where T : IComparable 将方法转换为通用方法应该足以使其工作。

public static bool IsInRange<T>(this T value, T lowerBound, T upperBound ) 
    where T : IComparable {

    return value != null && lowrBound != null && upperBound !=null
           && lowerBound.CompareTo(value) <= 0 && value.CompareTo(upperBound) <= 0;
}