声明一个C#Generic Type方法

时间:2015-01-05 20:22:25

标签: c# generics

我有一个班级:

internal class Paginated<T> where T : class
{
    public List<T> data { get; set; }

    public int total { get; set; }
    public int page { get; set; }
    public int per_page { get; set; }
    public Paging paging { get; set; }
}

在另一个班级,我有方法:

public T RequestAllPaginated<T>() where T : Paginated<AnyType> //AnyType???
{
    var item = Request<T>();

    //Get all data from paging property
    if(item != null)
    {
        var i = item as Paginated<AnyType>; //AnyType???
        var data = i.data;

    }

    return item;
}

T始终是Paginated<AnyType>类型。问题是我如何在RequestAllPaginated方法声明中确定并稍后将其投射?

1 个答案:

答案 0 :(得分:3)

试试这个解决方案

public T RequestAllPaginated<T, TK>() where T : Paginated<TK> where TK : class
{
    var item = Request<T>();

    //Get all data from paging property
    if(item != null)
    {
        var i = item as Paginated<TK>;
        var data = i.data;

    }

    return item;
}

替代解决方案:

public Paginated<T> RequestAllPaginated<T>() where T : class
{
    var item = Request<Paginated<T>>();

    //Get all data from paging property
    if(item != null)
    {
        var i = item as Paginated<T>;
        var data = i.data;

    }

    return item;
}