I have class that works a bit like the Linq To Sql Where
clause.
它从一个陈词树上建立了一系列行动。
The expression tree is an Expression<Func<bool>>
(i.e. a lambda without arguments that returns a bool)
conditionBuilder.BuildCondition(() => x != 3 && y != 5);
The class works fine for normal
expressions like the example above but now I need the functionality to combine expressions.
I have added And, Or methods like
var exp1 = () => x != 3;
var exp2 = () => y != 5;
var exp = ConditionBuilder.And(exp1, exp2);
但它在结合若干表述时变得复杂。
我谨写信。
var exp = exp1 && exp2;
but since I can t directly overload operator && I need to find some other solution.
The tricky part is that resulting operations does not have a boolean overload for the bitwise operators. i.e. the result of exp1 & exp2 is int and not bool. (I can get around this by adding != 0
)
So my questions now are:
- Will it be confusing if I let operator & be a logical expression (i.e. AndAlso)?
- operator && will work if I overload & / true / false but that will also create an implicit boolean conversion. I know implicit boolean conversion is something you want to avoid in C++ but I am not sure how it matters i C#. Also, should the overridden true and false evaulate the expression? (i.e. what should
if (exp1)
do?)
Edit: I already have working code like this:
public class ConditionBuilder
{
private readonly Expression<Func<bool>> _filter;
public ConditionBuilder(Expression<Func<bool>> filter) {
_filter = filter;
}
public static ConditionBuilder And(ConditionBuilder left, ConditionBuilder right) {
return new ConditionBuilder(Expression.Lambda<Func<bool>>(Expression.AndAlso(left._filter.Body, right._filter.Body)));
}
public static ConditionBuilder Or(ConditionBuilder left, ConditionBuilder right) {
return new ConditionBuilder(Expression.Lambda<Func<bool>>(Expression.OrElse(left._filter.Body, right._filter.Body)));
}
}
Edit 2 to clarify the questions.
这些用语改为另一种格式。 例如,() => ConditionsBuilder。 Int Field(123) = 5
改为123 EQ 5
。 (真正的形式是别的,但你们还是有这种想法)
问题在于,其他方式的拖网对双向操作者而言具有超重负荷。 这意味着:(>) => real & false
被转换成True BITAND False
,因其返回的不是纯洁而没有有效表述。
如果我超负荷工作,就是指AndAlso
exp1 & exp2
有效表述,
() => x != 3 & y != 5
不是。
My second question was if having an implicit conversion to bool causes problems in C# like it does in C++.