Domanda

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'

Please let me know one solution. Thanks in advance

È stato utile?

Soluzione

Since the class PagedData<T> has a constraint on the type parameter T, you have to explicitly replicate that constraint on your own method:

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top