[英]Expression of type 'System.DateTime' cannot be used for return type 'System.Object'
I've created an expression that I'm using for sorting which works fine, until I hit a DateTime
field, where I get the following error (on the second line): 我创建了一个表达式,我正在使用它进行排序工作正常,直到我点击DateTime
字段,我得到以下错误(在第二行):
Expression of type 'System.DateTime' cannot be used for return type 'System.Object' 'System.DateTime'类型的表达式不能用于返回类型'System.Object'
Here's my code: 这是我的代码:
ParameterExpression param = Expression.Parameter(typeof(MyEntity), "x");
Expression<Func<MyEntity, object>> sortExpression =
Expression.Lambda<Func<AMyEntity, object>>(
Expression.Property(param, sortKey), param);
Can anyone help at all? 任何人都可以帮忙吗?
Just add a conversion in there: 只需在其中添加转化:
Expression<Func<MyEntity, object>> sortExpression =
Expression.Lambda<Func<AMyEntity, object>>(
Expression.Convert(
Expression.Property(param, sortKey),
typeof(object)),
param);
You appear to be expecting auto-boxing of value-types to match the return-type of the expression. 您似乎期望自动装箱值类型以匹配表达式的返回类型。 Unfortunately, Expression.Lambda
does not do this. 不幸的是, Expression.Lambda
没有这样做。
You can use Expression.Convert
to perform the boxing. 您可以使用Expression.Convert
执行装箱。
var body = Expression.Convert(Expression.Property(param, sortKey), typeof(object));
var sortExpression = Expression.Lambda<Func<AMyEntity, object>>(body, param);
If for some reason you don't want the conversion operation to be present in the expression if the property is already a reference-type, you can branch as required: 如果由于某种原因,如果属性已经是引用类型,则不希望转换操作出现在表达式中,您可以根据需要进行分支:
Expression body = Expression.Property(param, sortKey);
if(body.Type.IsValueType)
body = Expression.Convert(body, typeof(object));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.