A brief analysis of generic class interface definitions

  • 2020-05-17 06:15:59
  • OfStack

The most basic generic class is defined as follows:


public abstract class GetDataBase<T> :IHttpHandler, IRequiresSessionState {
 protected abstract T GetModel(HttpContext context);
 protected abstract IList<T> GetList(int pageSize, int pageIndex, string where, string sortname, string sortorder, out int total);  
    protected JsonFlexiGridData GetFlexiGridData(IList<T> list, int pageIndex, int pageSize, int total, string colkey, string colsinf) 
    {
        PagedList<T> pl = new PagedList<T>();
        pl.PageIndex = pageIndex - 1;
        pl.PageSize = pageSize;
        pl.DataList = new List<T>();
        pl.DataList.AddRange(list);
        pl.Total = total;
        JsonFlexiGridData data = JsonFlexiGridData.ConvertFromPagedList(pl, colkey, colsinf.Split(','));
        return data;   
    }

}

The simplest is simply adding < T > pl.DataList = new List.DataList = new List < T > (a); Always prompt error, the compilation does not pass, say must be a class can, so modify as follows

public abstract class GetDataBase<T> :IHttpHandler, IRequiresSessionState where T : class{

1. Set generic base classes or requirements
where T: class means that the type is a class, and of course if you need T to be another type, such as an interface, or to inherit from a class, you can modify it in the same way
For example, the generic interface inherits from the generic interface IObjectWithKey < TK > .

public interface IDeviceAgent<TK, TCk> : IObjectWithKey<TK>, IDisposable{

For example, the generic interface IContainer of type 1, TV, must inherit from the interface IObjectWithKey < TK >

public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{

Generics have multiple types

public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{

There are multiple types, and of course, in a concrete class, the two types can be the same or different
So it's going to be at 1, right < > If you have several types, you can put a few parameters. Do you have any special requirements for names
3. What if generics have multiple type constraints, such as class requirements

public abstract class GetDataBase<TListItem, TModel> : IHttpHandler, IRequiresSessionState
    where TListItem : class
    where TModel : class


Related articles: