如何比较泛型类型的值? [英] How to compare values of generic types?

查看:25
本文介绍了如何比较泛型类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较泛型类型的值?

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).

那么,两个问题:

  1. 为什么我们会观察到这种奇怪的行为?是什么让我们无法比较已知IComparable的泛型类型的值?这不是以某种方式违背了通用约束的全部目的吗?
  2. 我该如何解决这个问题,或者至少要解决这个问题?
  1. 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?
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆