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

这一生的挚爱 提交于 2019-12-04 12:59:35

Depending on how you use result you could create it dynamically with the delegate type Func<Entity, long> and type it as a LambdaExpression:

ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "e");
Expression propertyAccess = Expression.Property(entityParameter, property);
var funcType = typeof(Func<,>).MakeGenericType(typeof(Entity), property.PropertyType);
LambdaExpression result = Expression.Lambda(funcType, propertyAccess, entityParameter);

Short answer: no, it is not possible. Value types need to be boxed to be seen as objects. The compiler does it for you normally, but if you build code yourself (e.g expression trees), you need to specify it as an explicit conversion, the way you see it in the found answer. If you cannot have it as a non-generic LambdaExpression, I would handle the convert case additionally where you expect the MemberExpression, or use PropertyInfo, and construct the orderby Expression only in the last moment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!