简体   繁体   English

比较通用方法C#中的两个值

[英]Comparing Two values in a generic method c#

I think my code is self explanatory about what i want to achieve : 我认为我的代码可以自我解释我想要实现的目标:

private bool Comparison<T>(T operatorOne, T operatorTwo, string operand)
    {
        switch (operand.ToLower())
        {
            case "=":
                return operatorOne.Equals(operatorTwo);
            case "<":
                return operatorOne < operatorTwo;
            case ">":
                return operatorOne > operatorTwo;
            case "contains":
                return operatorOne.ToString().Contains(operatorTwo.ToString());
            default:
                return false;
        }
    }

It gives me error : 它给我错误:

Error   16  Operator '>','<' cannot be applied to operands of type 'T' and 'T'

I need a method that can compare strings, Int,Double, chars. 我需要一个可以比较字符串,Int,Double和chars的方法。 Note: Exclude the condition that strings will be passed for > or < check OR Int will be sent for "contains" check 注意:排除要为>或<check传递字符串的条件,否则将为“包含”校验发送Int

You could use Comparer<T>.Default.Compare(operatorOne, operatorTwo) for comparation. 您可以使用Comparer<T>.Default.Compare(operatorOne, operatorTwo)进行比较。 Please be aware that if T does not implement IComparable and IComparable<T> , Comparer<T>.Default.Compare throws an exception. 请注意,如果T没有实现IComparableIComparable<T> ,则Comparer<T>.Default.Compare会引发异常。

To make sure that T implements IComparable , you may add where T: IComparable constraint. 为了确保T实现IComparable ,可以where T: IComparable约束中添加。 (It will exclude classes which implement IComparable<T> , but not IComparable . Still may be acceptable, since many classes which implement IComparable<T> , implement IComparable too.) (这将排除的实施类IComparable<T> 但不是 IComparable 。可能仍然是可接受的,因为它们实现许多类IComparable<T>实现IComparable太)。

private bool Comparison<T>(T operatorOne, T operatorTwo, string operand)
    where T: IComparable
{
    switch(operand.ToLower())
    {
        case "=":
            return Comparer<T>.Default.Compare(operatorOne, operatorTwo) == 0;
        case "<":
            return Comparer<T>.Default.Compare(operatorOne, operatorTwo) < 0;
        case ">":
            return Comparer<T>.Default.Compare(operatorOne, operatorTwo) > 0;
        case "contains":
            return operatorOne.ToString().Contains(operatorTwo.ToString());
        default:
            return false;
    }
}

PS 聚苯乙烯

As Servy suggested, you may also pass IComparer as an extra parameter to the function. 正如Servy建议的那样,您也可以将IComparer作为附加参数传递给函数。 It would allow to cover types which implement neither IComparable nor IComparable<T> , so Comparer<T>.Default does not work for them. 它将允许覆盖既不实现IComparable也不实现IComparable<T> ,因此Comparer<T>.Default不适用于它们。

Also, credits go to @TimothyShields , who suggested Comparer<T>.Default . 另外, 感谢@TimothyShields ,他建议使用Comparer<T>.Default

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

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