gpt4 book ai didi

c# - 如何动态指定 List<> 函数的类型?

转载 作者:太空狗 更新时间:2023-10-29 21:23:21 26 4
gpt4 key购买 nike

我有一些表示数据库表的类,用于将每个表的行加载到 DataGridView 上,我有一个 List<>在循环内获取该表中所有行的函数。

public List<class_Table1> list_rows_table1()
{
// class_Table1 contains each column of table as public property
List<class_Table1> myList = new List<class_Table1>();

// sp_List_Rows: stored procedure that lists data
// from Table1 with some conditions or filters
Connection cnx = new Connection;
Command cmd = new Command(sp_List_Rows, cnx);

cnx.Open;
IDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
class_Table1 ct = new class_Table1();

ct.ID = Convert.ToInt32(dr[ID_table1]);
ct.Name = dr[name_table1].ToString();
//... all others wanted columns follow here

myList.Add(ct);
}
dr.Close();
cnx.Close();

// myList contains all wanted rows; from a Form fills a dataGridView
return myList();
}

而对于其他的表,还有一些其他的函数:list_rows_table2, list_rows_table3...我的问题是:如何创建一个唯一的 List<>函数,我可以在其中动态指定 List<> 的类型返回,或如何转换,例如 List<object>List<myClass>回来之前。

最佳答案

您可以拥有所有数据类都必须实现的接口(interface)

public interface IData
{
void FillFromReader(IDataReader dr);
}

然后像这样改变你的方法

public List<T> GetList<T>(string sqlText)
where T : IData, new()
{
List<T> myList = new List<T>();

using (Connection cnx = new Connection(connString))
using (Command cmd = new Command(sqlText, cnx)) {
cnx.Open();
using (IDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
T item = new T();
item.FillFromReader(dr);
myList.Add(item);
}
}
}
return myList();
}

所以基本上每个类都会负责填充自己的字段。

通用类型参数的约束 where T : IData, new() 至关重要。它告诉方法,T 必须实现接口(interface) IData。这对于能够在不强制转换的情况下调用方法 FillFromReader 是必需的。数据类必须有一个默认构造函数(这由 new() 指定。这使您可以使用 new T() 实例化一个。


我用 using 语句包围了使用连接、命令和数据读取器的代码。 using 语句在 block 的末尾自动关闭和释放资源,并确保发生这种情况,即使应该抛出异常或语句 block 应该过早地留下 return-statement 例如.

参见 using Statement (C# Reference)

关于c# - 如何动态指定 List<> 函数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com