您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

浅析泛型类接口定义

作者:佚名    责任编辑:admin    更新时间:2022-06-22

在使用泛型定义类的过程中遇到了不少问题,特记录如下,需要的朋友可以参考下  

定义最基本的泛型类如下:

复制代码 代码如下:
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;  
    }

}


其实最简单的只需要添加<T>,就表示泛型类了,可在使用的过程中 pl.DataList = new List<T>();总是提示错误,编译不通过,说是必须是类才可以,于是修改如下

复制代码 代码如下:
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{


例如泛型接口IContainer的第一类型TV必须继承与接口IObjectWithKey<TK>

复制代码 代码如下:
public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{


2泛型有多个类型

复制代码 代码如下:
public interface IContainer<TK, TV> where TV:IObjectWithKey<TK>{


就有多个类型,当然,在具体的类中,这两种类型可以相同,也可以不同
其实也就是在一对<>中放置多个类型,有几个类型,就放几个参数,名称没有什么特殊要求
3泛型如果有多个类型约束,例如都要求是类,如何处理

复制代码 代码如下:


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