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

时间:2016-09-22 22:34:40

标签: c# generics extension-methods

我写了一个通用扩展方法来查看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以便我可以进行编译?

1 个答案:

答案 0 :(得分:3)

使用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;
}