我想使用LINQ表达式的一些动态特征。 我需要的,或者和不表达。我提不起太大..
我们要检查某些功能是否已启用或没有在我们的系统,并基于我们会决定是否显示菜单项或不。 我们已经形成了以XML格式的规则,我所知道的转换规则AST,但我不知道映射到LINQ表达式。
规则是这样的:Feature1Enabled而Feature2Eenabled或(Feature3Disabled而不是Feature5Enabled)
这里的“Feature1Enabled”,“Feature2Eenabled”等都是该功能的名称。 我们将这个字符串传递给IsFeatureEnabled功能检查功能是否已经启用。
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<string, string, bool>> 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")
}
我想相当于布尔结果= IsFeatureEnabled( “MV”, “”)&& IsFeatureEnabled( “气体”, “G”)|| !IsFEatureEnabled( “气”, “F”)
Linq中的表达形式。不过,我可以将它们转换为动态地根据我的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<Func<string, string, bool>> featureEnabledExpTree =
Expression.Lambda<Func<string, string, bool>>(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<Func<bool>> test =
Expression.Lambda<Func<bool>>(
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<Func<bool>> featureEnabledExpTree = () =>
IsFeatureEnabled("MV", "") &&
IsFeatureEnabled("GAS", "G") ||
!IsFEatureEnabled("GAS", "F");