C# use an operation as a parameter
I'm trying to make a function where I can give it an operation >
<
==
!=
etc.
I was wondering if it is possible to set one of these as a parameter to a function,
ie: UseOperator("test", >, 0)
If not what would be the best way to handle something like this? Maybe开发者_如何学编程 an enum?
The most natural approach would be to pass a delegate, IMO, e.g. of type Func<int, int, bool>
. Unfortunately you can't convert an operator directly to a delegate - but you could write methods pretty simply and use method group conversions:
public void UseOperator(string name, Func<int, int, bool> op, int value)
{
...
}
public static bool GreaterThan(int x, int y, value)
{
return x > y;
}
UseOperator("test", GreaterThan, 0);
Marc Gravell's work on generic operators in MiscUtil may be useful to you.
This is not possible but you could use function delegates:
UseOperator("test", (x, y) => x > y, 0);
How about parsing the operator as a string value?
UseOperator("Test", ">", 0)
private void UseOperator(string str1, string operator, int intVlue)
{
switch(operator)
{
case ">":
//.....
}
}
精彩评论