How to create NotStartsWith Expression tree
I'm using jqGrid
to display some data to users. jqGrid has search functionality that does string compares like Equals, NotEquals, Contains, StartsW开发者_如何学运维ith, NotStartsWith, etc.
When I use StartsWith
I get valid results (looks like this):
Expression condition = Expression.Call(memberAccess,
typeof(string).GetMethod("StartsWith"),
Expression.Constant(value));
Since DoesNotStartWith doesn't exist I created it:
public static bool NotStartsWith(this string s, string value)
{
return !s.StartsWith(value);
}
This works, and I can create a string and call this method like so:
string myStr = "Hello World";
bool startsWith = myStr.NotStartsWith("Hello"); // false
So now I can create/call the expression like so:
Expression condition = Expression.Call(memberAccess,
typeof(string).GetMethod("NotStartsWith"),
Expression.Constant(value));
But I get a ArgumentNullException was unhandled by user code: Value cannot be null.
Parameter name: method
error.
Does anyone know why this doesn't work or a better way to approach this?
You're checking for method NotStartsWith
on type string, which doesn't exist. Instead of typeof(string)
, try typeof(ExtensionMethodClass)
, using the class where you put your NotStartsWith
extension method. Extension methods don't actual exist on the type itself, they just act like they do.
Edit: Also rearrange your Expression.Call
call like this,
Expression condition = Expression.Call(
typeof(string).GetMethod("NotStartsWith"),
memberAccess,
Expression.Constant(value));
The overload you are using expects an instance method, this overload expects a static method, based on the SO post you referred to. See here, http://msdn.microsoft.com/en-us/library/dd324092.aspx
i know the ask was answered, but another approach is available and simple:
Expression condition = Expression.Call(memberAccess,
typeof(string).GetMethod("StartsWith"),
Expression.Constant(value));
condition = Expression.Not(condition);
and... done! just have to negate the expression.
精彩评论