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

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

问题描述

我如何比较通用的类型的值?

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的,甚至是限制值类型(其中T:结构)的时候,我们还不能应用运营商和LT ;,>的任何,&LT; =,> =,==或!=。 (我知道,涉及的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的不超载的&GT; = 运营商。您应该使用

IComparable doesn't overload the >= operator. You should use

value.CompareTo(_minimumValue) >= 0

这篇关于如何比较通用类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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