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开发者_如何学Go 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");
精彩评论