gpt4 book ai didi

c# - 如何创建 NotStartsWith 表达式树

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:01 25 4
gpt4 key购买 nike

我正在使用 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 未被用户代码处理:值不能为空。
参数名称:方​​法
错误。

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

最佳答案

您正在检查不存在的字符串类型的方法 NotStartsWith。尝试 typeof(ExtensionMethodClass),而不是 typeof(string),使用放置 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

关于c# - 如何创建 NotStartsWith 表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7069393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com