gpt4 book ai didi

c# - 使用 System.Linq.Expressions API 重写 Lambda 表达式

转载 作者:行者123 更新时间:2023-11-30 17:44:33 24 4
gpt4 key购买 nike

我坚持了几个小时。我想要做的就是通过使用 Expression class APIs 重写以下表达式来构建一个表达式树。 :

var Expression<Func<T, bool>> expr = x => x.SomeProperty == value;

到目前为止我得到的是:

{
var param = Expression.Parameter(typeof(T), "x");
var lhs = Expression.Property(param, "SomeProperty");
var rhs = Expression.Constant(value, value.GetType());
return Expression.Call(typeof(object).GetMethod("Equals", BindingFlags.Static | BindingFlags.Public), lhs, rhs);
}

如果 T 是原始类型或枚举,这会很好地工作。但如果 T 是引用类型、class 等,我会得到一个异常。

异常信息:

Unable to create a constant value of type 'TypeName'. Only primitive types or enumeration types are supported in this context.

提前致谢。

最佳答案

在这种情况下,您不需要明确指定类型,只要该值不为 null(我假设它不是,因为您正在调用 GetType()在上面)。

应该这样做。

var param = Expression.Parameter(typeof(T), "x");
var property = Expression.Property(param, "SomeProperty");
var compareValue = Expression.Constant(value);
var equals = Expression.Equal(property, compareValue);
return Expression.Lambda<Func<T, bool>>(equals, param);

关于c# - 使用 System.Linq.Expressions API 重写 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29575562/

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