[英]Generic sort method with Func<T, TH> delegate
我想要做的是創建一個通用方法,它接受類型T
的列表以及一些搜索選項(即排序方向和排序字段),然后根據搜索選項對給定的列表進行排序。
我認為這個問題可能與我傳遞給 OrderBy 方法的 Func 委托的通用返回類型有關,但我不能完全確定說實話。 此刻被這件事難住了。 這是我到目前為止所擁有的:
public static class TableGenerationHelper
{
public static IList<T> CreateReportObject<T>(IList<T> items, ISearchOptions searchOptions) where T : new()
{
Type sortFieldType = typeof(T).GetProperty(searchOptions.SortField)?.GetType();
MethodInfo createMethod = typeof(TableGenerationHelper).GetMethod("CreateSortedList");
MethodInfo methodRef = createMethod?.MakeGenericMethod(typeof(T), sortFieldType);
Object[] args = { items, searchOptions.SortField, searchOptions.SortDirection };
results = (IList<T>)methodRef?.Invoke(null, args);
return results;
}
public static IList<T> CreateSortedList<T, TH>(IList<T> items, String sortField, String sortDirection) where T : new()
{
Type type = typeof(T);
PropertyInfo propInfo = type.GetProperty(sortField);
Func<T, TH> orderByFunc = x => (TH)propInfo?.PropertyType.GetRuntimeProperty(sortField)?.GetValue(x, null);
return LoadListOrderedByDirection(items, orderByFunc, sortDirection);
}
public static IList<T> LoadListOrderedByDirection<T, TH>(IList<T> items, Func<T, TH> keySelector, String sortDirection)
{
switch (sortDirection)
{
case "ASC":
return items.OrderBy(keySelector).ToList();
case "DESC":
return items.OrderByDescending(keySelector).ToList();
default:
return items;
}
}
}
沒有拋出異常,但沒有進行排序。 原始列表將按照傳遞的順序返回。 很感謝任何形式的幫助。
編輯
對於此處明顯缺乏實際問題,我深表歉意。 老實說,我在發帖時沒有意識到這一點。
也感謝您對空運算符的建議。 這給我的印象是代碼正常工作,而實際上它應該拋出異常。 這使得調試過程非常令人沮喪,因為在單步執行代碼時似乎沒有任何問題。
正如 StriplingWarrior 在他的回復中提到的,我在我的 lambda 表達式中使用的是RuntimePropertyInfo
而不是PropertyInfo
。
下次我發帖時,我肯定會有一個實際的問題。
您正在吃一堆空值,這會導致您錯過一些您可能應該看到異常的錯誤,而 Eric Lippert 是對的,您確實需要學習逐步調試代碼以進行調試。
你這里有幾個錯誤。
propInfo
上使用PropertyType
,它為您提供屬性返回的類型,而不是聲明屬性的對象類型。 然后,您要為具有給定名稱的屬性請求該類型(這對我來說沒有多大意義,因為您首先已經通過調用 GetProperty 獲得了 PropertyInfo)。GetProperty
的結果上使用GetType()
,它將始終返回運行時屬性信息類的類型,而不是屬性的實際類型。 您想改用PropertyType
。這似乎工作正常:
public static IList<T> CreateReportObject<T>(IList<T> items, ISearchOptions searchOptions) where T : new()
{
Type sortFieldType = typeof(T).GetProperty(searchOptions.SortField).PropertyType;
MethodInfo createMethod = typeof(TableGenerationHelper).GetMethod("CreateSortedList");
MethodInfo methodRef = createMethod?.MakeGenericMethod(typeof(T), sortFieldType);
Object[] args = { items, searchOptions.SortField, searchOptions.SortDirection };
var results = (IList<T>)methodRef?.Invoke(null, args);
return results;
}
public static IList<T> CreateSortedList<T, TH>(IList<T> items, String sortField, String sortDirection) where T : new()
{
Type type = typeof(T);
PropertyInfo propInfo = type.GetProperty(sortField);
Func<T, TH> orderByFunc = x =>
{
return (TH)propInfo.GetValue(x, null);
};
return LoadListOrderedByDirection(items, orderByFunc, sortDirection);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.