我有以下方法:
private List<TSource> Sort<TSource, TKey>(
List<TSource> list,
Func<TSource, TKey> sorter,
SortDirection direction)
{
...
}
并且根据情况,参数Func<TSource,TKey>
会发生变化,例如,我有以下开关:
public class CustomType
{
string Name {get; set;}
string Surname {get; set;}
...
}
switch (sortBy)
{
case "name":
orderedList = this.Sort<CustomType, string>(
lstCustomTypes,
s => s.Name.ToString(),
direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
break;
case "surname":
orderedList = this.Sort<CustomType, string>(
lstCustomTypes,
s => s.Surname.ToString(),
direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
break;
}
因此,正如您在这些情况下所观察到的那样,除了 lambda 参数之外,调用总是相同的s => something
,s => something2
所以对于没有重复代码,我想要类似于:
switch (sortBy)
{
case "name":
lambdaExpresion = s => s.Name.ToString();
break;
case "surname":
lambdaExpresion= s => s.Surname.ToString();
break;
}
orderedList = this.Sort<CustomType, string>(
lstCustomTypes,
lambdaExpresion,
direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
我不确定是否可能,但如果可以,如何实现?我不想重复代码。