问题
How can I pass a bitwise operator as a parameter to my method? I've read some articles that describes how to pass for example equality operator as a parameter however they implement it in some way and after this pass it with a delegate. In my case I'm not sure how to implement the bitwise operator.
回答1:
You can use Func<>
int MyFunc(int input1, int input2, Func<int, int, int> bitOp)
{
return bitOp(input1, input2);
}
Use like this
Console.WriteLine(MyFunc(1, 2, (a, b) => a | b));
Outputs "3"
回答2:
Appreciate the answer has already been accepted at this point, but thought I would at least share another possible approach:
int result = Bitwise.Operation(1, 2, Bitwise.Operator.OR); // 3
Declared as:
public static class Bitwise
{
public static int Operation(int a, int b, Func<int, int, int> bitwiseOperator)
{
return bitwiseOperator(a, b);
}
public static class Operator
{
public static int AND(int a, int b)
{
return a & b;
}
public static int OR(int a, int b)
{
return a | b;
}
}
}
来源:https://stackoverflow.com/questions/36106018/c-sharp-pass-bitwise-operator-as-parameter