亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號