为了账号安全,请及时绑定邮箱和手机立即绑定

Net Core:查找类中任何变量字段的数据类型

Net Core:查找类中任何变量字段的数据类型

C#
MMMHUHU 2023-09-16 17:45:52
如何获取此 OrderBy 表达式树并使其接受任何订单类型(int、float、string、boolean 等)?是否可以?现在它的类型转换为仅字符串。我应该在调用方法时将所有内容都转换为字符串,还是有更好的方法来使更通用?我只需要 T 类中这个 propertyName 的数据类型,这样我就可以将其放在下面的函数中。测试这些,还没有运气。成员类型、GetType()、字段类型Net Core Linq 中的 OrderBy 表达式树用于扩展方法创建表达式:public static class ExpressionTreesExtesion{    public static Expression<Func<T,string>> OrderByExpression<T>(this IEnumerable<T> enumerable, string propertyName)    {        var propInfo = typeof(T).GetProperty(propertyName);        var collectionType = typeof(T);        var parameterExpression = Expression.Parameter(collectionType, "x");        var propertyAccess = Expression.MakeMemberAccess(parameterExpression, propInfo);        var orderExpression = Expression.Lambda<Func<T,string>>(propertyAccess, parameterExpression);        return orderExpression;    }}如何致电:var ProductExpression = records.OrderByExpression("Name");var result  = records.OrderBy(ProductExpression.Compile());ProductExpression.Compile() above will compile into x => x.Name, where column name is supplied at the run-time
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

由于类型在编译时未知,因此您将无法使用强类型返回类型,例如Expression<Func<T,TKey>>.


public static class ExpressionTreesExtension {

    static readonly Type funcTTResult = typeof(Func<,>);

    public static IOrderedQueryable<T> OrderByProperty<T>(this IEnumerable<T> enumerable, string propertyName) {

        var itemType = typeof(T);

        var propertyInfo = itemType.GetProperty(propertyName);

        var propertyType = propertyInfo.PropertyType;

        // Func<T,TPropertyType>

        var delegateType = funcTTResult.MakeGenericType(itemType, propertyType);

        // T x =>

        var parameterExpression = Expression.Parameter(itemType, "x");

        // T x => x.Property

        var propertyAccess = Expression.Property(parameterExpression, propertyInfo);

        // Func<T,TPropertyType> = T x => x.Property

        var keySelector = Expression.Lambda(delegateType, propertyAccess, parameterExpression);


        var query = enumerable.AsQueryable();


        // query.OrderBy(x => x.Property)

        MethodCallExpression orderByExpression = Expression.Call(

             typeof(Queryable),

             "OrderBy",

             new[] { query.ElementType, propertyInfo.PropertyType },

             query.Expression, keySelector);


        // Create an executable query from the expression tree. 

        return (IOrderedQueryable<T>)query.Provider.CreateQuery<T>(orderByExpression);

    }

}

并使用像

//IEnumerable<Person> records...
var data = records.OrderByProperty("Name");


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信