声明 Func<in T,out Result>动态地 [英] Declaring Func<in T, out Result> dynamically
问题描述
考虑一下:
var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
现在我要声明
Func<int,orderType>
我知道这是不可能的,因为 ordertype
是在运行时,但有什么解决方法吗?
I know its not possible directly since ordertype
is at runtime but is there is any workaround ?
这正是我想要做的:
var propertyinfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
var param = Expression.Parameter(typeof(T), "x");
var sortExpression = (Expression.Lambda<Func<T, orderType>>
(Expression.Convert(Expression.Property(param, sortExpressionStr), typeof(orderType)), param));
这一切都是因为我想转换:
all this because I want to convert:
Expression<Func<T,object>> to Expression<Func<T,orderType>>
或者如果不可能,那么我想从一开始就用正确的类型创建它,情况如下:
or if its not possible then I want to create it from the first place with the right type , the case is as following:
我在一个具有 type(Customer)
和该类型的属性名称的方法中,我想通过它进行排序,我想创建一个排序表达式树以将其传递给 <代码>Orderby(这里).
I'm inside a method which have a type(Customer)
and a property name of that type I want to order by it , I want to create a sort expression tree to pass it to Orderby
(here).
推荐答案
linqClass.OrderBy(GetSortExpression(sortstr));
public static Expression<Func<T,object>> GetSortExpression<T>(string sortExpressionStr)
{
var param = Expression.Parameter(typeof(T), "x");
var sortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortExpressionStr), param);
return sortExpression;
}
这有效,我的问题是我过去常常传递额外的参数 Typeof(Object) 和 orderby 用来告诉我它不能按对象类型排序.谢谢大家
this worked my problem was i used to pass extra parameter Typeof(Object) and orderby used to tell me it cant sort by Object type. thanks all
感谢 dtb,我会检查您的答案是否也有效,如果有效,我将接受它,如果无效,我将接受该答案.
thanks dtb i will check if your answer work too and i will accept it if it works if not i will accept thsi one.
这篇关于声明 Func<in T,out Result>动态地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!