C# Pass bitwise operator as parameter

≡放荡痞女 提交于 2020-01-14 03:15:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!