首页 > 解决方案 > 类型化数据集作为通用返回类型

问题描述

我有两种返回类型化数据集的方法。我只想有一种通用方法。

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 ;
         }
      }
   }
}

标签: c#.netgenerics

解决方案


这应该相当简单,只需将您的方法签名更改为使用泛型类型并添加约束,例如:

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 查询绝对可以是任何东西,所以你需要非常小心它们。


推荐阅读