Identify the operator and use it in several places?

let's say I have this code here:

if(Something)
    condition |= Class1.Class2.SomeId;
else
    condition &= Class1.Class2.SomeId; 

The code is the same except for & = and | = . Can I somehow create 2 "variables" of the operator and just use them in the code, for example:

condition "myoperator" Class1.Class2.SomeId;

Thank: -)

+3
source share
4 answers

No, you cannot do what you ask, but lambda expressions can be used at the same end.

Func<int, int, int> op;
if (Something)
{
  op = (x, y) => x | y;
}
else
{
  op = (x, y) => x & y;
}

condition = op(condition, Class1.Class2.SomeId);
+2
source

No. However, you can make a function for everyone.

if (Something)
    idOr(ref condition, Class1.Class2.SomeId);
else
    idAnd(ref condition, Class1.Class2.SomeId);


function idOr(ref condition, whatever ID) {
    condition |= ID;
}
function idAnd(ref condition, whatever ID) {
    condition &= ID;
}
+2
source

( )

SomeId , , msdn ( ).

0

You can dynamically generate a function to implement the operator you need:

public Func<T, T, T> GetOperator<T>(ExpressionType exprType)
{
    var p1 = Expression.Parameter(typeof(T), "p1");
    var p2 = Expression.Parameter(typeof(T), "p2");
    var expr = Expression.MakeBinary(exprType, p1, p2);
    var lambda = Expression.Lambda<Func<T, T, T>>(expr, p1, p2);
    return lambda.Compile();
}

...

var op = GetOperator<int>(Something ? ExpressionType.Or : ExpressionType.And);
condition = op(condition, Class1.Class2.SomeId);

But this is probably overkill ... if you don't need a general solution, just use Brian's solution.

0
source

Source: https://habr.com/ru/post/1754607/


All Articles