看起来没有可重用的 .NET Framework 组件来解决问题中提出的要求。然而,Andrey Shchekin 的 工具参考为如何编写所需的组件提供了很好的参考。
这是一个解决顺序 Not() 运算符的取消、将 Not() 运算符分配到二进制表达式以及 De Morgan 定律的应用的片段。
public class NotCollapser : ExpressionVisitor
{
// Incomplete list; others removed for brevity.
private static readonly IDictionary<ExpressionType, Func<BinaryExpression, BinaryExpression>> NotDistributionMap =
{
{ ExpressionType.Equal, e => Expression.MakeBinary(ExpressionType.NotEqual, e.Left, e.Right) },
{ ExpressionType.NotEqual, e => Expression.MakeBinary(ExpressionType.Equal, e.Left, e.Right) },
{ ExpressionType.GreaterThan, e => Expression.MakeBinary(ExpressionType.LessThanOrEqual, e.Left, e.Right) },
{ ExpressionType.AndAlso, e => Expression.MakeBinary(ExpressionType.OrElse, Expression.Not(e.Left), Expression.Not(e.Right)) },
{ ExpressionType.OrElse, e => Expression.MakeBinary(ExpressionType.AndAlso, Expression.Not(e.Left), Expression.Not(e.Right)) }
};
protected override Expression VisitUnary(UnaryExpression expression)
{
if (expression.NodeType == ExpressionType.Not)
{
if (expression.Operand.NodeType == ExpressionType.Not)
{
return Visit((expression.Operand as UnaryExpression).Operand);
}
if (NotDistributionMap.ContainsKey(expression.Operand.NodeType))
{
var distribute = NotDistributionMap[expression.Operand.NodeType];
return Visit(distribute(expression.Operand as BinaryExpression));
}
}
return base.VisitUnary(expression);
}
}