使用泛型类作为列表创建对象

时间:2016-03-25 14:57:27

标签: c# generics

我遇到这种情况:

public class ExtResult<T>
{
    public bool Success { get; set; }
    public string Msg { get; set; }
    public int Total { get; set; }
    public T Data { get; set; }
}

//create list object:
List<ProductPreview> gridLines;
...
...
//At the end i would like to create object
ExtResult<gridLines> result = new ExtResult<gridLines>() { 
    Success = true, Msg = "", 
    Total=0, 
    Data = gridLines 
}

但是我收到了一个错误:

  

错误:&#34;无法解析gridLines&#34;

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:4)

gridLines是一个变量,其类型为List<ProductPreview>,您应将其用作ExtResult<T>的类型参数:

ExtResult<List<ProductPreview>> result = new ExtResult<List<ProductPreview>>() { 
    Success = true, 
    Msg = "", 
    Total=0, 
    Data = gridLines 
};

答案 1 :(得分:2)

您应该将类​​型作为泛型参数传递,而不是变量:

var result = new ExtResult<List<ProductPreview>> // not gridLines, but it's type
{ 
    Success = true,
    Msg = "",
    Total=0,
    Data = gridLines
}