为List<T>创建分页排序扩展方法时泛型相关报错如何解决?
问题解决方案
报错根因
- 第一个报错
the type or namespace T could not be found的原因是方法未声明泛型参数T,编译器无法识别该未知类型 - 第二个报错
extension method must be defined in a non-generic static class的原因是C#语法规范明确要求:扩展方法必须定义在非泛型静态类中,将承载类改为泛型类违反了该规则
正确实现
正确的做法是保持承载类为非泛型静态类,将泛型参数T定义在方法级别:
using System.Reflection; public static class DataTools { // 泛型参数<T>声明在方法名称后 public static List<T> ToPaging<T>(this List<T> list, int pageNumber, int count, string orderField, OrderType orderType) { if (list == null || !list.Any()) return new List<T>(); PropertyInfo prop = typeof(T).GetProperty(orderField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (prop == null) throw new ArgumentException($"类型 {typeof(T).Name} 不存在可访问的公开实例字段 {orderField}"); // 排序逻辑 IOrderedEnumerable<T> ordered = orderType == OrderType.Asc ? list.OrderBy(x => prop.GetValue(x)) : list.OrderByDescending(x => prop.GetValue(x)); // 分页逻辑 return ordered.Skip((pageNumber - 1) * count).Take(count).ToList(); } } // 排序类型枚举 public enum OrderType { // 升序 Asc, // 降序 Desc }
调用示例
// 示例:查询商品列表第1页,每页20条,按价格降序排序 List<Goods> goodsList = GetGoodsListFromDb(); List<Goods> pagedList = goodsList.ToPaging(1, 20, "Price", OrderType.Desc);
内容的提问来源于stack exchange,提问作者Ali.Rashidi
相关产品推荐
相关产品推荐

