我有这个方法
public Expression<Func<Auction, bool>> GetUnsetDatesAuctionsExpression()
{
if (condition)
return GetAllUnsetDatesAuctionsExpression();
else
return (a =>
(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey) &&
((a.Starts == null) || (a.Ends == null)));
}
}
调用此方法
private Expression<Func<Auction, bool>> GetAllUnsetDatesAuctionsExpression()
{
return (a => (a.Starts == null) || (a.Ends == null));
}
问题是在上面的公共方法中我有以下行
(a.Starts == null) || (a.Ends == null)
与私有方法中表达式的主体相同。
现在,这样做当然不起作用,因为你不能和一个bool和一个表达式
return (a =>
(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey) &&
(GetAllUnsetDatesAuctionsExpression));
所以,问题是,如何将对私有方法的调用与
结合起来(membershipUser.ProviderUserKey != null) &&
(a.OwnerReference == (Guid)membershipUser.ProviderUserKey)
答案 0 :(得分:3)
创建一个新表达式作为两者的组合,请参阅BinaryExpression:
System.Linq.Expressions.BinaryExpression binaryExpression =
System.Linq.Expressions.Expression.MakeBinary(
System.Linq.Expressions.ExpressionType.AndAlso,
firstExpression,
secondExpression);
答案 1 :(得分:1)
尝试以下方法(我删除了多余的括号):
return a =>
membershipUser.ProviderUserKey != null &&
a.OwnerReference == (Guid)membershipUser.ProviderUserKey &&
GetAllUnsetDatesAuctionsExpression().Compile()(a);
// ---------------------------------^^^^^^^^^^^^^
上面的代码使用Expression.Compile方法将表达式树描述的lambda表达式(由GetAllUnsetDatesAuctionsExpression()
方法返回)编译成可执行代码,并生成一个代表lambda表达式的委托。
编辑:我没有注意到您的公共方法返回了表达式,而不是值。在您的方案中,Hans Kesting's approach当然要好得多。
答案 2 :(得分:0)
你能否改变这个表达式:
return (a => (a.Starts == null || a.Ends == null));