类型' 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);