“System.DateTime”类型的表达式不能用于返回类型“System.Object”
我创建了一个用于排序的表达式,该表达式工作正常,直到我点击 DateTime
字段,出现以下错误(在第二行):
“System.DateTime”类型的表达式不能用于返回类型 '系统.对象'
这是我的代码:
ParameterExpression param = Expression.Parameter(typeof(MyEntity), "x");
Expression<Func<MyEntity, object>> sortExpression =
Expression.Lambda<Func<AMyEntity, object>>(
Expression.Property(param, sortKey), param);
任何人都可以提供帮助吗?
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):
Expression of type 'System.DateTime' cannot be used for return type
'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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在其中添加一个转换即可:
Just add a conversion in there:
您似乎期望值类型的自动装箱与表达式的返回类型相匹配。不幸的是,
Expression.Lambda
不执行此操作。您可以使用
Expression.Convert
来执行拳击。如果由于某种原因您不希望在属性已经是引用类型的情况下在表达式中出现转换操作,您可以根据需要进行分支:
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.You can use
Expression.Convert
to perform the boxing.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: