如何在 C# 中使用表达式树动态地进行 NULL 检查并执行 ToLower 调用以及 Contains 调用

问题描述 投票:0回答:1

我正在尝试动态生成以下表达式

x => x?.ToLower().Contains(value?.ToLower())

在我的

Item
课上。

这是我的

Item class

public class Item
{
    public string? Type { get; set; }
}

我能够使用以下代码进行

NULL
检查和
Contains
调用。

var param = Expression.Parameter(typeof(Item), "i");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });

var itemTypeMember = Expression.Property(param, "Type");
var itemTypeNullCheck = Expression.Equal(itemTypeMember, Expression.Constant(null));
var itemTypeConstant = Expression.Constant(itemType, typeof(string));
var itemTypeBody = Expression.Call(itemTypeMember, containsMethod, itemTypeConstant);
var itemTypeCondition = Expression.Condition(itemTypeNullCheck, Expression.Constant(false), itemTypeBody);

var lambda = Expression.Lambda<Func<Item, bool>>(itemTypeCondition, param);

Query.Where(lambda);

到目前为止一切顺利。这按预期工作。我达到了

x => x?.Contains(value)

但是这样做的问题是它不是不区分大小写的比较。

现在,当我尝试使用上面的代码添加

ToLower()
时,

MethodInfo toLowerMethod = typeof(string).GetMethod("ToLower", new[] { typeof(string) });

var itemTypeBody = Expression.Call(Expression.Call(itemTypeMember, toLowerMethod), containsMethod, itemTypeConstant);

我收到以下错误。

Value cannot be null. (Parameter 'method')
System.ArgumentNullException: Value cannot be null. (Parameter 'method')
   at System.ArgumentNullException.Throw(String paramName)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method)

请帮助我解决我所缺少的内容。

c# lambda expression-trees
1个回答
1
投票

ToLower
上没有接受
string
参数的
string
方法。
this
不算数:

typeof(string).GetMethod("ToLower", Array.Empty<Type>())
© www.soinside.com 2019 - 2024. All rights reserved.