简体   繁体   中英

Comparison Operator in C#

I have a vague requirement. I need to compare two values. The values may be a number or a string.

I want to perform these operations >, <, ==,<>, >=,<=

In my method I will pass, the parameter1, parameter 2 and the operators of above.

How can compare the two values based on the operator as effectively in .NET 2.0.

My method should be as simplified for both String and integer input values.

Sample Input Value:

param1  |  param2  |  operator
------------------------------
David      Michael       >
1          3             ==

Provided both parameters are always of the same type you could use a generic method where both parameters implement IComparable<T> (introduced in .NET 2.0)

public int CompareItems<T>(T item1, T item2) where T: IComparable<T>
{
    return item1.CompareTo(item2);
}

(You can interpret the result of CompareTo() depending on the operator your pass in your implementation)

If you have to/want to build generic version you need to pass comparison as function/lambda - it is not possible to use operators in generic way. Somithing like:

class OpComparer<T>
{
  Func<T,T,bool> operation;
  public OpComparer(Func<T,T,bool> op)
  {
    operation = op;
  }

  int PerformOp(T item1, T item2) 
  {
    return operation(item1, item2);
  }
}

...
var comparerLess = new OpCompared<String>((a,b)=> a < b );
var result = comparerLess.PerformOp("aaa", "bbb");

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