是否可以创建匿名类型泛型?

wal*_*ter 1 c# asp.net anonymous-types

我已经构建了一个适用于特定数据类型的分页类,但现在我需要使类型动态化

这是我的代码

public class Pagination {
    public IQueryable<Character> Items { get; set; }

    public int PageSize { get; set; }

    public int TotalPages {
        get {
            if (this.Items.Count() % this.PageSize == 0)
                return this.Items.Count() / this.PageSize;
            else
                return (this.Items.Count() / this.PageSize) + 1;
        }
    }

    public Pagination(IQueryable<Character> items, int pageSize) {
        this.PageSize = pageSize;
        this.Items = items;
    }

    public IQueryable<Character> GetPage(int pageNumber) {
        pageNumber = pageNumber - 1;
        return this.Items.Skip(this.PageSize * pageNumber).Take(this.PageSize);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,此分页类仅适用于"Character",是否可以创建匿名数据类型并调用Skip和Take等通用方法?

Ali*_*tad 5

是的,您可以将类创建为泛型类:

public class Pagination<T> {
    public IQueryable<T> Items { get; set; }

    public int PageSize { get; set; }

    public int TotalPages {
        get {
            if (this.Items.Count() % this.PageSize == 0)
                return this.Items.Count() / this.PageSize;
            else
                return (this.Items.Count() / this.PageSize) + 1;
        }
    }

    public Pagination(IQueryable<T> items, int pageSize) {
        this.PageSize = pageSize;
        this.Items = items;
    }

    public IQueryable<T> GetPage(int pageNumber) {
        pageNumber = pageNumber - 1;
        return this.Items.Skip(this.PageSize * pageNumber).Take(this.PageSize);
    }
}
Run Code Online (Sandbox Code Playgroud)