我有两种返回类型化数据集的方法。 我只想有一种通用方法。
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 ;
}
}
}
}
答案 0 :(得分:1)
这应该非常简单,只需将方法签名更改为使用通用类型并添加约束,例如:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: nr-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/server-snippet: |
location = / {
proxy_pass http://localhost:1880/;
}
spec:
tls:
- secretName: tls-secret1
hosts:
- my.server.name
rules:
- host: my.server.name
http:
paths:
- path: /nr
backend:
serviceName: my-nodered-node-red
servicePort: 1880
现在可以这样调用该方法:
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
中,以便可以在方法内部创建实例。
注意:此方法的主要问题在于SQL查询绝对可以是任何东西,因此您需要非常小心。