gpt4 book ai didi

c# - 将返回表达式的方法引用到另一个方法的语法?

转载 作者:太空狗 更新时间:2023-10-29 21:50:43 25 4
gpt4 key购买 nike

我找到了一段如下形式的代码:

public static Expression<Func<Invoice, CustomerContact>> GetCustomerContact()
{
return i => new CustomerContact {
FirstName = i.Customer.FirstName,
LastName = i.Customer.LastName,
Email = i.Customer.Email,
TelMobile = i.Customer.TelMobile,
};
}

在代码的其他部分,我想获得相同的轻量级 CustomerContact 对象,只是不是从 Invoice,而是从 Customer 本身。所以显而易见的事情是:

public static Expression<Func<Customer, CustomerContact>> GetCustomerContact()
{
return c => new CustomerContact {
FirstName = c.FirstName,
LastName = c.LastName,
Email = c.Email,
TelMobile = c.TelMobile,
};
}

然后更改以 Invoice 作为输入的 Expression 以引用此方法,即如下所示:

public static Expression<Func<Invoice, CustomerContact>> GetCustomerContact()
{
return i => GetCustomerContact(i.Customer); // doesn't compile
}

正确的语法是什么?

最佳答案

您可以使用 Expression.Invoke :

var paramExpr = Expression.Parameter(typeof(Invoice), "i");
var propertyEx = Expression.Property(paramExpr, "Customer");

var body = Expression.Invoke(GetCustomerContactFromCustomer(), propertyEx);

return Expression.Lambda<Func<Invoice, CustomerContact>>(body, paramExpr);

请注意,某些 LINQ 提供程序在此类调用表达式方面存在问题。

解决此问题(并为您提供更方便的语法)的最简单方法是使用 LINQKit :

var expr = GetCustomerContactFromCustomer();   
Expression<Func<Invoice, CustomerContact>> result = i => expr.Invoke(i.Customer);
return result.Expand();

关于c# - 将返回表达式的方法引用到另一个方法的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881247/

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