Define an operator and use it in several places?
lets say I have this code here:
if(Something)
condition |= Class1.Class2.SomeId;
else
condition &= Class1.Class2.SomeId;
The code is the same except for the &= and |=. Can I somehow create 2 operator "variables" and just use them in the code, like this:
condi开发者_开发技巧tion "myoperator" Class1.Class2.SomeId;
Thanks :-)
No, you cannot do exactly what you are asking, but lambda expressions could be used to 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);
No. You could make a function for each, though.
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;
}
You can overload only operators of you own classes (not of Boolean)
if condition or SomeId is of your class, you can overload any operator that is on that msdn page (you cannot create entirely new operators).
You could 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 that's probably overkill... if you don't need a generic solution, just use Brian's solution.
精彩评论