【发布时间】:2017-12-26 07:05:34
【问题描述】:
我编写了下面的代码来评估布尔表达式。表达式以对象的形式编码。
这是我查看代码并思考的时刻之一:我确信有更好的编码方法,使用更少的布尔变量但看不到正确的方法。有什么帮助吗?已编写单元测试并通过各种输入。
if (tree == null || !tree.IsActive || tree.FilterNodes == null)
{
return false;
}
var result = false;
foreach (var filter in tree.FilterNodes.Where(a => a.IsActive && a.ConditionNodes != null))
{
var tempBool = false;
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
if (filter.LogicalOperator == LogicalOperator.Or && ApplyCondition(condition.ConditionOperator, value, condition.FieldValue))
{
tempBool = true;
break;
}
else if (filter.LogicalOperator == LogicalOperator.And)
{
tempBool = ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if (!tempBool)
{
break;
}
}
else
{
tempBool = false;
}
}
else if (!string.IsNullOrWhiteSpace(condition.FieldName) && filter.LogicalOperator == LogicalOperator.And)
{
tempBool = false;
}
}
result = tempBool;
if (!result)
{
break;
}
}
return result;
【问题讨论】:
-
我知道有点晚了,但你试过Shunting yard algorithm吗?我实现了一些类似的东西,但我评估表达式字符串而不是对象。可以看看here。
标签: c# boolean expression boolean-logic boolean-expression