基于AST使用And Or和Not表达的C#表达式

我想将Linq表达式用于某些动态function。 我需要And,Or和Not表达式..我不能得到太多……

我们想检查我们的系统中是否启用了某些function,并根据该function决定是否显示菜单项。 我们已经形成了XML格式的规则,我知道将规则转换为AST但我不知道要映射到Linq表达式。

规则如下:Feature1Enabled和Feature2Eenabled或(Feature3Disabled而非Feature5Enabled)

这里“Feature1Enabled”,“Feature2Eenabled”等是该function的名称。 我们将此字符串传递给IsFeatureEnabled函数以检查是否已启用某项function。

public delegate bool IsEnabledDelegate(string name, string value); public static bool IsFeatureEnabled(string name, string value) { if (name == "MV") return true; if (name == "GAS" && value == "G") return true; //More conditions goes here return false; } static void Main(string[] args) { Expression<Func> featureEnabledExpTree = (name, value) => IsFeatureEnabled(name, value); //I want the equal of the following statement in C# Linq Expression bool result = IsFeatureEnabled("MV", "") && IsFeatureEnabled("GAS", "G") || !IsFEatureEnabled("GAS", "F") } 

我希望等效于bool结果= IsFeatureEnabled(“MV”,“”)&& IsFeatureEnabled(“GAS”,“G”)|| !IsFEatureEnabled(“GAS”,“F”)

in Linq expression Format ..但是我可以根据我的AST表示法动态转换它们。

非常感谢..如果您需要更多信息,请在评论中告诉我..

  ParameterExpression name = Expression.Parameter(typeof(string), "name"), value = Expression.Parameter(typeof(string), "value"); // build in reverse Expression body = Expression.Constant(false); body = Expression.Condition( Expression.AndAlso( Expression.Equal(name, Expression.Constant("GAS")), Expression.Equal(value, Expression.Constant("G")) ), Expression.Constant(true), body); body = Expression.Condition( Expression.Equal(name, Expression.Constant("MV")), Expression.Constant(true), body); Expression> featureEnabledExpTree = Expression.Lambda>(body, name, value); // test in isolation var featureEnabledFunc = featureEnabledExpTree.Compile(); bool isMatch1 = featureEnabledFunc("MV", "") && featureEnabledFunc("GAS", "G") || !featureEnabledFunc("GAS", "F"); 

然后,如果您还需要第二部分作为表达式树:

  //I want the equal of the following statement in C# Linq Expression Expression> test = Expression.Lambda>( Expression.OrElse( Expression.AndAlso( Expression.Invoke(featureEnabledExpTree, Expression.Constant("MV"), Expression.Constant("") ), Expression.Invoke(featureEnabledExpTree, Expression.Constant("GAS"), Expression.Constant("G") ) ), Expression.Not( Expression.Invoke(featureEnabledExpTree, Expression.Constant("GAS"), Expression.Constant("F") ) ) ) ); bool isMatch = test.Compile()(); 

像那样?

 Expression> featureEnabledExpTree = () => IsFeatureEnabled("MV", "") && IsFeatureEnabled("GAS", "G") || !IsFEatureEnabled("GAS", "F");