这是我的Expression扩展方法,可将InBetweenStr
功能添加到Expression(System.Linq.Expressions.Expression
)类。但是,我想暗示字符串比较忽略大小写,所以我修改了StringComparisonExpression
并添加了第三个参数:StringComparison.CurrentCultureIgnoreCase
。但当然代码不起作用并抛出一个异常,说:“为调用方法Int32 Compare(System.String, System.String, System.StringComparison)
提供的参数数量不正确”。
所以我想知道除了从StringComparison.CurrentCultureIgnoreCase
string.Compare
作为第三个参数传递给Expression.Call
之外,还有一种优雅的方法可以使字符串比较不区分大小写
代码:
// for InBetweenStr and NotInBetweenStr
public static Expression<Func<int>> StringComparisonExpression = () => string.Compare(null, null);
public static MethodInfo StringComparisonExpressionhMethodInfo = ((MethodCallExpression) StringComparisonExpression.Body).Method;
public static Expression InBetweenStr(this Expression value, Expression lowerBound, Expression upperBound)
{
// zero constant expression
var zeroExpr = Expression.Constant(0);
return Expression.AndAlso(
Expression.GreaterThanOrEqual(Expression.Call(StringComparisonExpressionhMethodInfo, value, lowerBound), zeroExpr),
Expression.LessThanOrEqual(Expression.Call(StringComparisonExpressionhMethodInfo, value, upperBound), zeroExpr)
);
}
修改后的StringComparisonExpression
导致异常:
public static Expression<Func<int>> StringComparisonExpression = () => string.Compare(null, null, StringComparison.CurrentCultureIgnoreCase);
答案 0 :(得分:3)
您可以获得MethodInfo
三参数string.Compare
方法,如下所示:
private static readonly MethodInfo StringComparisonExpressionMethodInfo =
typeof(string).GetMethod("Compare", new Type[] {
typeof(string), typeof(string), typeof(StringComparison)
});
使用此MethodInfo
,您可以使用第三个参数调用该方法:
var ignoreCase = Expression.Constant(StringComparison.CurrentCultureIgnoreCase);
return Expression.AndAlso(
Expression.GreaterThanOrEqual(Expression.Call(StringComparisonExpressionMethodInfo, value, lowerBound, ignoreCase), zeroExpr),
Expression.LessThanOrEqual(Expression.Call(StringComparisonExpressionMethodInfo, value, upperBound, ignoreCase), zeroExpr)
);
由于您为第三个参数传递常量,因此使ignoreCase
常量表达式与您zeroExpr
的方式相同。