gpt4 book ai didi

c# - 使用类型转换动态构建表达式树

转载 作者:行者123 更新时间:2023-11-30 16:52:34 25 4
gpt4 key购买 nike

(已编辑):

我有我的课:

public class Employee
{
public int Id {get;set;}
public string Name {get;set;}
}

public class ContractEmployee : Employee
{
public int ContractMonth {get;set;}
}

public class Remuneration
{
public int Id {get;set;}
public Employee Employee {get;set;}
public int Amount {get;set;}
}

我可以像这样查询契约(Contract)月份(使用员工作为基本类型):

1st case:

r => (r.Employee as ContractEmployee).Amount > 10000 

Corrected:

r => (r.Employee is ContractEmployee) && r.Amount > 10000

2nd case:

_context.Remunerations.Where(r => (r.Employee as ContractEmployee).ContractMonth > 10);

我需要创建这个表达式

r => (r.Employee as ContractEmployee).ContractMonth > 10

动态地。

假设,我得到这个字符串“Employee.ContractMonth > 10”,并且它会知道我需要在编码时将它转换为 ContractEmployee。

我可以将其转换为如下表达式:

PropertyInfo p = typeof(Remuneration).GetProperty("Employee.ContractMonth");
ParameterExpression lhsParam = Expression.Parameter(typeof(Remuneration));
Expression lhs = Expression.Property(lhsParam, p);
Expression rhs = Expression.Constant(Convert.ChangeType("10", pi.PropertyType));
Expression myoperation = Expression.MakeBinary(ExpressionType.GreaterThan, lhs, rhs);

上面的代码将不起作用,因为“ContractMonth”不属于类“Employee”。

How can I typecast Employee as ContractEmployee using Expression Tree:r => (r.Employee as ContractEmployee).ContractMonth > 10

谢谢

最佳答案

您正在尝试访问错误对象的属性。

你有

r => (r.Employee as ContractEmployee).Amount > 10000 

虽然它应该是:

r => (r.Employee is ContractEmployee) && r.Amount > 10000

我将由您根据此 lambda 构建表达式

像这样:

Expression.And(
Expression.TypeIs(Expression.Parameter(typeof(Employee), "r"), typeof(ContractEmployee)),
Expression.GreaterThan(Expression.Property(Expression.Parameter(typeof(Employee), "r"), "Ammount"), Expression.Constant(10000))
)

关于c# - 使用类型转换动态构建表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32420550/

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