如何比较泛型类型的值? [英] How to compare values of generic types?
问题描述
如何比较泛型类型的值?
How do I compare values of generic types?
我已将其缩减为最小样本:
I have reduced it to a minimal sample:
public class Foo<T> where T : IComparable
{
private T _minimumValue = default(T);
public bool IsInRange(T value)
{
return (value >= _minimumValue); // <-- Error here
}
}
错误是:
运算符>="不能应用于T"和T"类型的操作数.
Operator '>=' cannot be applied to operands of type 'T' and 'T'.
到底是什么!?T
已经被约束为 IComparable
,即使将其约束为值类型(where T: struct
),我们仍然无法应用任何<
, >
, <=
, >=
, ==
或 !=
.(我知道对于 ==
和 !=
存在涉及 Equals()
的解决方法,但它对关系运算符没有帮助).
What on earth!? T
is already constrained to IComparable
, and even when constraining it to value types (where T: struct
), we still can't apply any of the operators <
, >
, <=
, >=
, ==
or !=
. (I know that workarounds involving Equals()
exist for ==
and !=
, but it doesn't help for the relational operators).
那么,两个问题:
- 为什么我们会观察到这种奇怪的行为?是什么让我们无法比较已知为
IComparable
的泛型类型的值?这不是以某种方式违背了通用约束的全部目的吗? - 我该如何解决这个问题,或者至少要解决这个问题?
- Why do we observe this weird behaviour? What keeps us from comparing the values of generic types which are known to be
IComparable
? Doesn't it somehow defeat the entire purpose of generic constraints? - How do I resolve this, or at least work around it?
(我意识到已经有一些与这个看似简单的问题相关的问题 - 但没有一个线程给出了详尽或可行的答案,所以在这里.)
(I realize there are already a handful of questions related to this seemingly simple problem - but none of the threads gives an exhaustive or workable answer, so here.)
推荐答案
IComparable
不会重载 >=
运算符.你应该使用
IComparable
doesn't overload the >=
operator. You should use
value.CompareTo(_minimumValue) >= 0
这篇关于如何比较泛型类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!