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

发布于 2024-12-28 07:20:08 字数 468 浏览 1 评论 0原文

我创建了一个用于排序的表达式,该表达式工作正常,直到我点击 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦纸 2025-01-04 07:20:08

只需在其中添加一个转换即可:

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

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);
鱼窥荷 2025-01-04 07:20:08

您似乎期望值类型的自动装箱与表达式的返回类型相匹配。不幸的是,Expression.Lambda 不执行此操作。

您可以使用 Expression.Convert 来执行拳击。

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

如果由于某种原因您不希望在属性已经是引用类型的情况下在表达式中出现转换操作,您可以根据需要进行分支:

Expression body = Expression.Property(param, sortKey);

if(body.Type.IsValueType)
   body = Expression.Convert(body, typeof(object));

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.

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文