简体   繁体   English

如何比较相同泛型类型的两个值?

[英]How I can compare two values of same generic type?

Following code won't compile:以下代码将无法编译:

class Test<T> where T : class, IComparable
{
    public bool IsGreater(T t1, T t2)
    {
        return t1 > t2; // Cannot apply operator '>' to operands of type 'T' and 'T'
    }
}

How I can make it work?我怎样才能让它工作? I want it to work for T = int , double , DateTime , etc.我希望它适用于 T = intdoubleDateTime等。

The IComparable interface that you have used here as the type constraint gives you a CompareTo method.您在此处用作类型约束的IComparable接口为您提供了一个CompareTo方法。 So you can do something like this:所以你可以做这样的事情:

public bool IsGreater(T t1, T t2)
{
    return t1.CompareTo(t2) > 0;
}

While currently you can't do exactly that (and you need to use solution by @DavidG ) there is a preview feature you can enable called generic math which is based on static abstract interface members and ships with interface specially for that purpose:虽然目前您无法完全做到这一点(并且您需要使用@DavidG 的解决方案),但您可以启用称为通用数学的预览功能,该功能基于静态抽象接口成员并带有专门用于该目的的接口:

[RequiresPreviewFeatures]
public interface IComparisonOperators<TSelf, TOther> : IComparable, IComparable<TOther>, IEqualityOperators<TSelf, TOther>, IEquatable<TOther> where TSelf : IComparisonOperators<TSelf, TOther>
{
    static bool operator <(TSelf left, TOther right);

    static bool operator <=(TSelf left, TOther right);

    static bool operator >(TSelf left, TOther right);

    static bool operator >=(TSelf left, TOther right);
}

So in future (or right now if you want to be an early adopter) you will be able to do (if no major overhaul comes for this preview):因此,将来(或现在,如果您想成为早期采用者)您将能够做到(如果此预览版没有大修):

class Test<T> where T : IComparisonOperators<T, T>
{
    public bool IsGreater(T t1, T t2)
    {
        return t1 > t2; 
    }
}

Note that for Test to support int , double , DateTime , etc. you need to remove class constraint (with or without this preview feature).请注意,要使Test支持intdoubleDateTime等,您需要删除class约束(有或没有此预览功能)。

You can use this to compare two values of same generic type.您可以使用它来比较相同泛型类型的两个值。

public bool IsGreater(T t1, T t2)
{
    return t1.CompareTo(t2) > 0;
}

Just let .NET compare for you:让 .NET 为您进行比较

public bool IsGreater(T t1, T t2) => Comparer<T>.Default.Compare(t1, t2) > 0; 

Note, that you don't have to check for null请注意,您不必检查null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM