C# 如何实现可传入排序参数的通用巧克力分发方法以避免重复编码
解决方案
你可以通过传入Func<TSource, TKey>类型的排序键选择器作为参数,实现通用的分发方法,无需重复编写多个逻辑相似的方法。
通用方法实现代码
// TKey为排序字段的类型,Person为你的人员实体类名,可根据你实际的类名替换 public void DistributeChocolatesByRule<TKey>(int choc, Func<Person, TKey> orderKeySelector) { People = People.OrderBy(orderKeySelector).ToList(); ChocolatesDistributed(choc); }
调用示例
原有的按年龄、firstName、lastName分发的需求,直接调用通用方法传入对应字段选择器即可:
// 按年龄分发 DistributeChocolatesByRule(10, x => x.Age); // 按firstName分发 DistributeChocolatesByRule(10, x => x.FirstName); // 按lastName分发 DistributeChocolatesByRule(10, x => x.LastName);
如果需要支持倒序排序,可额外加一个重载方法:
public void DistributeChocolatesByRuleDesc<TKey>(int choc, Func<Person, TKey> orderKeySelector) { People = People.OrderByDescending(orderKeySelector).ToList(); ChocolatesDistributed(choc); } // 倒序调用示例:按年龄从大到小分发 DistributeChocolatesByRuleDesc(10, x => x.Age);
扩展说明
如果需要支持更复杂的多字段组合排序、自定义排序规则,你可以再重载一个接收IComparer<TKey>参数的版本,就能覆盖所有排序场景。
内容的提问来源于stack exchange,提问作者evesare
相关产品推荐
相关产品推荐

