如何创建NotStartsWith表达式树

时间:2011-08-15 19:01:26

标签: c# extension-methods linq-expressions

我正在使用jqGrid向用户显示一些数据。 jqGrid具有搜索功能,可以进行字符串比较,如Equals,NotEquals,Contains,StartsWith,NotStartsWith等。

当我使用StartsWith时,我得到了有效的结果(看起来像这样):

Expression condition = Expression.Call(memberAccess,
                typeof(string).GetMethod("StartsWith"),
                Expression.Constant(value));

由于DoesNotStartWith不存在,我创建了它:

public static bool NotStartsWith(this string s, string value)
{
    return !s.StartsWith(value);
}

这很有效,我可以创建一个字符串并像这样调用这个方法:

string myStr = "Hello World";
bool startsWith = myStr.NotStartsWith("Hello"); // false

所以现在我可以像这样创建/调用表达式:

Expression condition = Expression.Call(memberAccess,
                typeof(string).GetMethod("NotStartsWith"),
                Expression.Constant(value));

但我收到ArgumentNullException was unhandled by user code: Value cannot be null. Parameter name: method错误。

有谁知道为什么这不起作用或更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:5)

您正在检查类型字符串上的方法NotStartsWith,该字符串不存在。不要使用typeof(string),而是使用您放置typeof(ExtensionMethodClass)扩展方法的类,尝试NotStartsWith。扩展方法实际上并不存在于类型本身上,它们就像它们一样。

编辑:同样重新安排Expression.Call这样的电话,

Expression condition = Expression.Call(
            typeof(string).GetMethod("NotStartsWith"),
            memberAccess,
            Expression.Constant(value));

您正在使用的重载需要一个实例方法,此重载需要一个静态方法,基于您引用的SO帖子。见http://msdn.microsoft.com/en-us/library/dd324092.aspx

答案 1 :(得分:0)

我知道问题得到了回答,但另一种方法很简单:

Expression condition = Expression.Call(memberAccess,
                                       typeof(string).GetMethod("StartsWith"),
                                       Expression.Constant(value));

condition = Expression.Not(condition);

并且......完成了!只需要否定表达。

相关问题