简体   繁体   English

泛型类型的扩展方法

[英]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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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