声明Func键&LT;在T,出结果&GT;动态 [英] Declaring Func<in T, out Result> dynamically
问题描述
考虑一下:
VAR的PropertyInfo = typeof运算(客户).GetProperty(SORTEX pressionStr);
输入订单类型= propertyinfo.PropertyType;
现在我要声明
Func键&LT; INT,订单类型&GT;
我知道它不可能直接,因为订单类型
在运行时,但有什么解决方法吗?
这正是我想做的事:
VAR的PropertyInfo = typeof运算(T).GetProperty(SORTEX pressionStr);
输入订单类型= propertyinfo.PropertyType;VAR参数=前pression.Parameter(typeof运算(T),X);
VAR SORTEX pression =(前pression.Lambda&LT;&Func键LT; T,订单类型&GT;&GT;
(防爆pression.Convert(前pression.Property(参数,SORTEX pressionStr)的typeof(订单类型)),参数));
这一切都是因为我想转换:
防爆pression&LT;&Func键LT; T,对象&gt;&GT;到防爆pression&LT;&Func键LT; T,订单类型&GT;&GT;
或者其不可能的,那么我想从与正确类型的第一个地方创建它,案件如下:
我其中有一个类型(客户)
的方法和该类型我想通过它来订购的属性名称里面,我想创建一个排序的前pression树将它传递给排序依据
(在这里)。
linqClass.OrderBy(GetSortEx pression(sortstr));
公共静态防爆pression&LT;&Func键LT; T,对象&gt;&GT; GetSortEx pression&LT; T&GT;(字符串SORTEX pressionStr)
{
VAR参数=前pression.Parameter(typeof运算(T),X);
VAR SORTEX pression =前pression.Lambda&LT;&Func键LT; T,对象&gt;&GT;(防爆pression.Property(参数,SORTEX pressionStr),参数);
返回SORTEX pression;
}
这工作我的问题是我用来传递额外的参数typeof运算(对象)和排序依据曾经告诉我它不能排序按对象类型。感谢所有
由于DTB我会检查你的答案太的工作,如果它的作品如果没有,我会接受thsi一个我都会接受。
Consider this:
var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;
now I want to declare
Func<int,orderType>
I know its not possible directly since ordertype
is at runtime but is there is any workaround ?
this is exactly what I want to do :
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:
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;
}
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
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键&LT;在T,出结果&GT;动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!