简体   繁体   English

如何在C#中扩展泛型类并返回泛型类

[英]How to extend a Generic class and return a generic class in C#

I have a generic class 我有一个普通班

public class PagedData<T> where T : class
{
        public IEnumerable<T> Data { get; set; }
        public int CurrentPage { get; set; }
        public int TotalRowCount { get; set; }
        public int RowsPerPage { get; set; }
        public int NumberOfPages { get; set; }
}

I am going to extend the above class as shown below 我将扩展上述类,如下所示

public static PagedData<T> PagedResult<T>(this List<T> list)
{
     //some logic and return result as type PagedData<T>
     return null;
}

But it shows one buld error like 但是它显示了一个可能的错误

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'MyApplication.PagedData' 类型“ T”必须是引用类型,才能在通用类型或方法“ MyApplication.PagedData”中用作参数“ T”

Please let me know one solution. 请让我知道一个解决方案。 Thanks in advance 提前致谢

Since the class PagedData<T> has a constraint on the type parameter T , you have to explicitly replicate that constraint on your own method: 由于类PagedData<T>在类型参数T上具有约束,因此您必须在自己的方法上显式复制该约束:

public static PagedData<T> PagedResult<T>(this List<T> list) where T : class
{
     //some logic and return result as type PagedData<T>
     return null;
}

If you don't do this, it would be "possible" to call PagedResult<int> but then it would be impossible for it to return a PagedData<int> -- which is why the compiler complains. 如果您不这样做,则调用PagedResult<int>是“可能的”,但是它不可能返回PagedData<int> -这就是编译器抱怨的原因。

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

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