c# - 为 :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;
}
}
解决方案
如果所有 id 字段都属于同一类型,您可以定义一个接口IHaveId
并对类型参数使用约束:
public interface IHaveId
{
public int ID {get;}
}
public static Hashtable dbTableToHashTable<T>(string tableName) where T : IHaveId
推荐阅读
- python - SSL CERTIFICATE_VERIFY_FAILED 在 Windows 10 上安装 Python 包
- flutter - 自定义 InputTextField 的验证器
- java - java.lang.NoSuchMethodError: com.google.gson.Gson.newBuilder()Lcom/google/gson/GsonBuilder;
- reactjs - 元素类型无效(错误):得到“未定义”
- javascript - 如何在“if”语句中访问属性?
- python-3.x - 新密码问题,如何解码给定的加密代码?
- javascript - 如何使用 javascript 获取此 json 数据?
- rxjs - 如何让我的 observable 具有用于 NGRX 效果的值
- python - 为什么 Tesseract OCR 没有捕获正确的输出?如何解决?
- microsoft-edge - 使用组策略时,Edge PWA 未应用桌面快捷方式名称和图标