【问题标题】:Extension Method for List<T> with return type T返回类型为 T 的 List<T> 的扩展方法
【发布时间】:2021-10-14 17:08:18
【问题描述】:

我想为List&lt;T&gt; 类型创建一个扩展方法,以便我可以在其中限制、排序和分页我的数据。

到目前为止,我已经创建了一个这样的静态类:

public static class DataTools {
    public static List<T> ToPaging(this List<T> list, int PageNumber,int Count,string OrderField,OrderType OrderType) {
        return null;
    }
}

但我收到一条错误消息,指出 the type or namespace T could not be found

当我像这样使我的类通用时:

public static class DataTools<T> {
    public static List<T> ToPaging(this List<T> list, int PageNumber,int Count,string OrderField,OrderType OrderType) {
        return null;
    }
}

这次我收到一条错误消息:extension method must be defined in a non-generic static class

我不知道该怎么办。我只想创建一个扩展方法来“Page”在将数据发送到前面之前对其进行“分页”。

【问题讨论】:

    标签: c# static extension-methods


    【解决方案1】:

    方法上指定泛型参数,而不是类:

    public static class DataTools
    {
        public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
            int Count, string OrderField,OrderType OrderType)
        {
            return null;
        }
    }
    

    可以使用Func&lt;TSource,TKey&gt; 像LINQ 一样,而不是按名称指定字段,这可能会拼写错误:

    public static class DataTools
    {
        public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
            int Count, Func<T,TKey> selector,OrderType OrderType)
        {
            var query=(orderType == OrderType.Ascending)
                       ? list.OrderBy(selector)
                       : list.OrderByDescending(selector);
            return query.Skip( (PageNumber-1)*Count)
                        .Take(Count)
                        .ToList();
        }
    }
    

    假设有一个Customer 对象列表:

    class Customer
    {
        public int Id {get;set;}
        public string Name{get;set;}
        public string Address {get;set;}
    }
    
    ...
    var list=new List<Customer>();
    

    列表可以通过以下方式分页:

    var page=list.ToPaging(0,10, c=>c.Id, OrderType.Ascending);
    
    

    var page=list.ToPaging(0,10, c=>c.Name, OrderType.Ascending);
    
    

    【讨论】:

    • 很高兴知道:尽管现在这是一个通用方法,但您通常不必在调用中显式指定 T。编译器会根据你的参数推断它。
    • @PMF OP 没有询问如何调用该方法。错误出现在方法定义中。类型参数必须在方法本身中指定
    • 调用 ToPaging() 时必须指定类型吗?
    • @Ali.Rashidi 在大多数情况下不会,编译器将能够推断出类型。
    • @Ali.Rashidi 我就是这么说的:不,你可以用var result = myList.ToPaging(1, 2, "A", OrderType.None)调用它,编译器会检测列表的类型并隐式插入。
    【解决方案2】:

    基于this,创建扩展方法时需要考虑以下几点:

    1. 定义扩展方法的类必须是非泛型, 静态和非嵌套

    2. 每个扩展方法都必须是静态方法

    3. 扩展方法的第一个参数应该使用this 关键字。

    所以结果会是这样的:

    public static class DataTools
    {
        public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
            int Count, string OrderField,OrderType OrderType)
        {
            return null;
        }
    }
    

    【讨论】:

    • 它解决了我的问题,谢谢@Alireza Ahmadi
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2011-10-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多