如何创建NotStartsWith表达式树

Dar*_*rcy 1 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));
Run Code Online (Sandbox Code Playgroud)

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

public static bool NotStartsWith(this string s, string value)
{
    return !s.StartsWith(value);
}
Run Code Online (Sandbox Code Playgroud)

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

string myStr = "Hello World";
bool startsWith = myStr.NotStartsWith("Hello"); // false
Run Code Online (Sandbox Code Playgroud)

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

Expression condition = Expression.Call(memberAccess,
                typeof(string).GetMethod("NotStartsWith"),
                Expression.Constant(value));
Run Code Online (Sandbox Code Playgroud)

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

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

Kra*_*atz 5

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

编辑:同样重新安排你的Expression.Call通话,

Expression condition = Expression.Call(
            typeof(string).GetMethod("NotStartsWith"),
            memberAccess,
            Expression.Constant(value));
Run Code Online (Sandbox Code Playgroud)

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