gpt4 book ai didi

c# - 如何将 Expression> 转换为 Expression>

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:52 27 4
gpt4 key购买 nike

有没有办法转换Expression<Func<T, object>>Expression<Func<object, object>>

最佳答案

我以前不得不这样做......

public static class ExpressionHelper {
public static Expression<Func<object,object>> ConvertParameterToObject<T>(this Expression<Func<T,object>> source){
return source.ReplaceParametersWithBase<T,object,object>();
}

public static Expression<Func<TBase,TResult>> ReplaceParameterWithBase<T,TResult,TBase>(this Expression<Func<T,TResult>> lambda)
where T :TBase
{
var param = lambda.Parameters.Single();
return (Expression<Func<TBase,TResult>>)
ParameterRebinder.ReplaceParameters(new Dictionary<ParameterExpression, ParameterExpression>
{
{ param, Expression.Parameter(typeof (TBase), param.Name) }
}, lambda.Body);
}
}


public class ParameterRebinder : ExpressionVisitor
{

private readonly Dictionary<ParameterExpression, ParameterExpression> map;



public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{

this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();

}



public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{

return new ParameterRebinder(map).Visit(exp);

}



protected override Expression VisitParameter(ParameterExpression p)
{

ParameterExpression replacement;

if (map.TryGetValue(p, out replacement))
{

p = replacement;

}

return base.VisitParameter(p);

}

}

关于c# - 如何将 Expression<Func<T, object>> 转换为 Expression<Func<object, object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5989920/

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