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