问题描述
我有两个表达式:
public static Expression<Func<int, bool>> IsDivisibleByFive() {
return (x) => x % 5 == 0;
}
和
public static Expression<Func<int, bool>> StartsWithOne() {
return (x) => x.ToString().StartsWith("1");
}
我想创建一个新的表达式,同时应用表达式在我的代码中以不同的组合使用):
And I want to create a new expression that applies both at once (the same expressions are used all over my code in different combinations):
public static Expression<Func<int, bool>> IsValidExpression() {
return (x) => IsDivisibleByFive(x) && StartsWithOne(x);
}
然后执行:
public static class IntegerExtensions
{
public static bool IsValid(this int self)
{
return IsValidExpression().Compile()(self);
}
}
在我的代码中:
if (32.IsValid()) {
//do something
}
我有很多这样的表达式,我想定义一次,而不是在整个地方重复代码。
I have many such expressions that I want to define once instead of duplicating code all over the place.
谢谢。
推荐答案
如果您只是尝试将表达式正文与 AndAlso
表达式是指 x
参数表达式实际上是两个不同的参数(即使它们具有相同的名称)。为了做到这一点,你需要使用表达式树访问者来替换你想与一个单一的常见 x > ParameterExpression 。
The problem you'll run into if you just try combining the expression bodies with an AndAlso
expression is that the x
parameter expressions are actually two different parameters (even though they have the same name). In order to do this, you would need to use an expression tree visitor to replace the x
in the two expressions you want to combine with a single, common ParameterExpression
.
您可能需要查看,它为您提供了很大的帮助。结果应该如下所示:
You may want to look at Joe Albahari's PredicateBuilder library, which does the heavy lifting for you. The result should look something like:
public static Expression<Func<int, bool>> IsValidExpression() {
return IsDivisibleByFive().And(StartsWithOne());
}
这篇关于C#如何将两个表达式组合成一个新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!