2011-08-15 93 views
1

我正在使用jqGrid向用户显示一些数据。 jqGrid的具有搜索功能,做字符串比较喜欢平等相待,NotEquals,包含,StartsWith,NotStartsWith等如何创建NotStarts使用表达式树

当我使用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错误。

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

回答

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

+0

我将'typeof(string)'改为'typeof(MyExtensionClass)',但是我得到一个新的错误'静态方法需要空实例,非静态方法需要非空实例。参数名称:实例'。这是在另一个线程http://stackoverflow.com/questions/3695235/expression-equals/3695436#3695436问,但我不知道如何解决这个问题。 – Darcy

+0

看着那篇文章'Expression.Call'正在搜索你传递的方法信息的第一个参数,由于它的静态方法(非实例),这是行不通的。你必须使用'Expression.Call'的不同重载,就像这个http://msdn.microsoft.com/en-us/library/dd324092.aspx。首先给出方法信息,然后给出两个参数。 – Kratz

+0

感谢您提供Kratz的代码示例! NotStartsWith现在效果很好。我非常感谢帮助。 – Darcy

0

我知道问了回答,但另一种方法是使用简单:

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

condition = Expression.Not(condition); 

和...完成!只需要否定表达。