[英]How to convert Expression<Func<TSource,string>> to Expression<Func<object,string>>
I am creating an expression dynamically which I pass into some method but that method accepts that expression in different way. 我正在动态创建一个表达式,我将其传递给某个方法,但该方法以不同的方式接受该表达式。 It throws exception:
它抛出异常:
Object of type
'System.Linq.Expressions.Expression`1[System.Func`2[Common.Domain.ViewModels.Dealer.CustomerGridViewModel,System.String]]'
cannot be converted to type
'System.Linq.Expressions.Expression`1[System.Func`2[System.Object,System.String]]'
I have tried the answer from Using Expression to 'Cast' Func<object, object> to Func<T, TRet> but that is not working for me. 我尝试使用表达式将'Cast'Func <object,object>转换为Func <T,TRet>,但这对我不起作用。
My expression is 我的表达是
Expression<Func<CustomerViewModel, string>>
but I want result as 但我想要结果
Expression<Func<object, string>>
Despite the fact that such cast is dangerous as the target method isn't guaranteed to operate only on CustomerViewModel
, the following code makes adapter expression which accepts a parameter of Object
type, tries to cast it to the CustomerViewModel
and calls the original expression internally: 尽管这样的强制转换是危险的,因为目标方法不能保证只在
CustomerViewModel
上运行,但下面的代码使得适配器表达式接受Object
类型的参数,尝试将其强制转换为CustomerViewModel
并在内部调用原始表达式:
var objParam = Expression.Parameter(typeof(object));
var call = Expression.Invoke(inputExpression, Expression.Convert(objParam, typeof(Foo)));
var outputExpression = Expression.Lambda<Func<object, string>>(call, objParam);
where inputExpression
is an original expression of type Expression<Func<CustomerViewModel, string>>
and outputExpression
is new expression of type Expression<Func<object, string>>
which can be passed to your method. 其中
inputExpression
是Expression<Func<CustomerViewModel, string>>
类型的原始表达式,而outputExpression
是Expression<Func<object, string>>
类型的新表达式,可以传递给您的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.