是否可以将某种返回类型的lambda表达式转换为更特定类型的等效表达式? [英] Is it possible to convert a lambda expression of some return type to its equivalent expression of a more specific type?

查看:80
本文介绍了是否可以将某种返回类型的lambda表达式转换为更特定类型的等效表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Entity
{
    public int A { get; set; }
    public string B { get; set; }
}

Expression<Func<Entity,object>> expr = x => x.A;
Expression<Func<Entity,int>> exprAtRuntime = x => x.A;

Expression<Func<Entity,object>> expr2 = x => x.B;
Expression<Func<Entity,string>> expr2AtRuntime = x => x.B;

如何在运行时将expr转换为expr2类型?

How can I take expr and convert it to the type of expr2 at runtime?

同样,我需要对属性B执行相同的操作.我需要接受类型为Expression<Func<Entity,object>>的params数组,该数组表示访问对象的不同属性,因此它们都需要具有Entity类型和常规返回类型对象(如在此先驱问题中已回答).

Likewise, I need to do the same for property B. I need to accept a params array of type Expression<Func<Entity,object>> which represents accessing different properties of an object, so they all need to have the Entity type and the general return type of object (as answered in this precursor question).

但是从该表达式中,我需要为params数组的每个元素构造一个更强类型的版本(即,使用有关类型的信息,将Expression<Func<TEntity,object>>转换为特定于要访问的基础属性的类型Expression<Func<TEntity,TProperty>>实体类型上访问的属性的属性.该怎么做?

But from that expression, I need to construct it's more strongly-typed version for each element of the params array (i.e. convert Expression<Func<TEntity,object>> to a type specific to the underlying property being accessed Expression<Func<TEntity,TProperty>>, using information about the type of the property being accessed on the entity type. How can this be done?

推荐答案

为此,您可以使用ExpressionVisitor删除Convert(如果存在),然后修复委托类型:

To do this, you can use an ExpressionVisitor that removes the Convert (if it exists) and then fixes up the delegate type:

class RemoveConvertVisitor : ExpressionVisitor
{
    protected override Expression VisitUnary(UnaryExpression node) =>
        node.NodeType == ExpressionType.Convert ? node.Operand : base.VisitUnary(node);

    protected override Expression VisitLambda<T>(Expression<T> node) =>
        Expression.Lambda(Visit(node.Body), node.Parameters);
}

这篇关于是否可以将某种返回类型的lambda表达式转换为更特定类型的等效表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆