C# 将按位运算符作为参数传递
C# Pass bitwise operator as parameter
如何将按位运算符作为参数传递给我的方法?我读过一些描述如何将相等运算符作为参数传递的文章,但是他们以某种方式实现它,然后通过委托传递它。就我而言,我不确定如何实现按位运算符。
您可以使用 Func<>
int MyFunc(int input1, int input2, Func<int, int, int> bitOp)
{
return bitOp(input1, input2);
}
这样使用
Console.WriteLine(MyFunc(1, 2, (a, b) => a | b));
输出“3”
感谢答案此时已被接受,但我认为我至少会分享另一种可能的方法:
int result = Bitwise.Operation(1, 2, Bitwise.Operator.OR); // 3
声明为:
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;
}
}
}
如何将按位运算符作为参数传递给我的方法?我读过一些描述如何将相等运算符作为参数传递的文章,但是他们以某种方式实现它,然后通过委托传递它。就我而言,我不确定如何实现按位运算符。
您可以使用 Func<>
int MyFunc(int input1, int input2, Func<int, int, int> bitOp)
{
return bitOp(input1, input2);
}
这样使用
Console.WriteLine(MyFunc(1, 2, (a, b) => a | b));
输出“3”
感谢答案此时已被接受,但我认为我至少会分享另一种可能的方法:
int result = Bitwise.Operation(1, 2, Bitwise.Operator.OR); // 3
声明为:
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;
}
}
}