类型' System.DateTime'的表达式不能用于返回类型' System.Object' [英] Expression of type 'System.DateTime' cannot be used for return type 'System.Object'

查看:78
本文介绍了类型' System.DateTime'的表达式不能用于返回类型' System.Object'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个用于排序的表达式,该表达式可以正常工作,直到遇到 DateTime 字段,在该字段中出现以下错误(在第二行):

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):

类型'System.DateTime'的表达式不能用于返回类型'System.Object'

Expression of type 'System.DateTime' cannot be used for return type 'System.Object'

这是我的代码:

ParameterExpression param = Expression.Parameter(typeof(MyEntity), "x");

Expression<Func<MyEntity, object>> sortExpression =
    Expression.Lambda<Func<AMyEntity, object>>(
        Expression.Property(param, sortKey), param);

任何人都可以帮忙吗?

推荐答案

只需在其中添加转化:

Expression<Func<MyEntity, object>> sortExpression =
    Expression.Lambda<Func<AMyEntity, object>>(
        Expression.Convert(
            Expression.Property(param, sortKey),
            typeof(object)),
        param);

这篇关于类型&amp;#39; System.DateTime&amp;#39;的表达式不能用于返回类型&amp;#39; System.Object&#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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