简体   繁体   中英

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. Note: Exclude the condition that strings will be passed for > or < check OR Int will be sent for "contains" check

You could use Comparer<T>.Default.Compare(operatorOne, operatorTwo) for comparation. Please be aware that if T does not implement IComparable and IComparable<T> , Comparer<T>.Default.Compare throws an exception.

To make sure that T implements IComparable , you may add where T: IComparable constraint. (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.)

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. It would allow to cover types which implement neither IComparable nor IComparable<T> , so Comparer<T>.Default does not work for them.

Also, credits go to @TimothyShields , who suggested Comparer<T>.Default .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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