首页 > 解决方案 > 为 :get all" 查询使用泛型

问题描述

我正在尝试使用泛型来减少数据库中存储过程的数量,我已经成功地做到了。问题出现在下一步。DB 列映射到模型,所有表都有一个 ID 列。我想创建一个哈希表,其中 ID 字段广告键和模型作为对象。当我尝试这样做时,我得到一个编译时错误,T 没有 ID 定义。有没有办法做到这一点?

public static class DB_TableToHashTable
    {
        public static Hashtable dbTableToHashTable<T>(string tableName)
        {
            List<T> myList = GlobalConfig.Connection.GenericGetAll<T>(tableName);
            Hashtable table = new Hashtable();
            foreach (var item in myList)
            {

                table.Add(item.ID, item);

            }

            return table;
        }
    }

标签: c#generics

解决方案


如果所有 id 字段都属于同一类型,您可以定义一个接口IHaveId并对类型参数使用约束

public interface IHaveId
{
   public int ID {get;}
}

public static Hashtable dbTableToHashTable<T>(string tableName) where T : IHaveId

推荐阅读