c# - 类型化数据集作为通用返回类型
问题描述
我有两种返回类型化数据集的方法。我只想有一种通用方法。
private TypedDataSet GetData(string query, string tblName)
{
string conString = .... ;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (TypedDataSet tds = new TypedDataSet ())
{
sda.Fill(tds , tblName);
return tds ;
}
}
}
}
解决方案
这应该相当简单,只需将您的方法签名更改为使用泛型类型并添加约束,例如:
private T GetData<T>(string query, string tblName)
where T : DataSet, new()
{
string conString = .... ;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
// Use T here instead of TypedDataSet
using (T tds = new T())
{
sda.Fill(tds , tblName);
return tds;
}
}
}
}
现在可以像这样调用该方法:
var typedDataSet = GetData<TypedDataSet>("foo", "bar");
请注意,泛型类型约束是DataSet
为了确保您可以将其传递给SqlDataAdapter.Fill
方法,new()
以便您可以在方法内创建实例。
注意:这种方法的主要问题是 SQL 查询绝对可以是任何东西,所以你需要非常小心它们。
推荐阅读
- java - 如何检查 Apache kafka 代理连接是否成功?
- python - 转义格式错误的 xml 中的额外引号
- outlook-addin - 发布使用 Outlook 预览元素的 Outlook 加载项 - SupportsSharedFolders
- linux - 读取文件(列和循环)和 ssh
- mongodb - 如何从 mongodb 的嵌套模式中获取特定模式?
- oracle - 比较变量时如何在 where 语句中使用 CASE 和 IN
- python - 在自定义损失函数中迭代张量
- java - 如何从堆积条形图中删除未来日期
- angular - 向传单的图层控件添加多个叠加层
- javascript - 如何使用选项卡导航器而不是堆栈导航器将参数传递给路由