加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 动态声明Func

发布时间:2020-12-15 18:06:16 所属栏目:百科 来源:网络整理
导读:考虑一下: var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);Type orderType = propertyinfo.PropertyType; 现在我想宣布 Funcint,orderType 我知道它不可能直接因为ordertype是在运行时但有任何解决方法吗? 这正是我想要做的: var p
考虑一下:
var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;

现在我想宣布

Func<int,orderType>

我知道它不可能直接因为ordertype是在运行时但有任何解决方法吗?

这正是我想要做的:

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));

这一切都是因为我想转换:

Expression<Func<T,object>> to Expression<Func<T,orderType>>

或者如果它不可能那么我想从正确的类型的第一个地方创建它,案例如下:

我在一个方法里面有一个类型(Customer)和一个我要通过它订购的类型的属性名称,我想创建一个排序表达式树来将它传递给Orderby(这里).

解决方法

你可以使用 Type.MakeGenericType Method:
Type result = typeof(Func<,>).MakeGenericType(typeof(int),orderType);

这应该工作:

public static IQueryable<T> OrderByField<T>(
    IQueryable<T> q,string sortfield,bool ascending)
{
    var p = Expression.Parameter(typeof(T),"p");
    var x = Expression.Lambda(Expression.Property(p,sortfield),p);

    return q.Provider.CreateQuery<T>(
               Expression.Call(typeof(Queryable),ascending ? "OrderBy" : "OrderByDescending",new Type[] { q.ElementType,x.Body.Type },q.Expression,x));
}

从here开始.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读