简体   繁体   中英

Extension Method with Generic Type

How to create extension method for a generic type?

The below code returning error

Extension method can only be declared in non-generic, non-nested static class

Code:

public static class PagedList<T> where T : BaseEntity
{
    public static IEnumerable<T> ToPagedList(this IEnumerable<T> source, int pageNumber = 0, int pageSize = 5)
    {
        return source.Skip(pageNumber * pageSize).Take(pageSize);
    }
}

Any further implementation with this makes this work ?

Specify generic types directly on the method and make the class as the error says static and non-generic.

public static class PagedList
{
    public static IEnumerable<T> ToPagedList<T>(this IEnumerable<T> source, 
        int pageNumber = 0, int pageSize = 5) where T : BaseEntity
    {
        return source.Skip(pageNumber * pageSize).Take(pageSize);
    }
}

您应该收听错误消息,需要在非泛型类中声明扩展方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM