在使用泛型定义类的过程中遇到了不少问题,特记录如下:
定义最基本的泛型类如下:
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; } }
public abstract class GetDataBase<T> :IHttpHandler, IRequiresSessionState where T : class{1设定泛型基类或者要求
关键的一句where T : class就表示类型是类,当然如果需要T是其他类型,例如接口,或者是继承与某个类,也是同样的修改方法
例如泛型接口继承于泛型接口IObjectWithKey<TK>,
public interface IDeviceAgent<TK, TCk> : IObjectWithKey<TK>, IDisposable{
public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{
public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{
就有多个类型,当然,在具体的类中,这两种类型可以相同,也可以不同
其实也就是在一对<>中放置多个类型,有几个类型,就放几个参数,名称没有什么特殊要求
3泛型如果有多个类型约束,例如都要求是类,如何处理
public abstract class GetDataBase<TListItem, TModel> : IHttpHandler, IRequiresSessionState where TListItem : class where TModel : class
微软文档