【问题标题】:Typed dataset as generic return type类型化数据集作为通用返回类型
【发布时间】:2019-06-12 13:57:58
【问题描述】:

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

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

【问题讨论】:

  • 这里需要通用什么?
  • 返回值需要通用
  • 我只看到一个返回类型,即TypedDataset。除此之外请注意,在方法中返回该实例后,您将使用using 处理它,因此您无法使用它。
  • 你的意思是private T GetData<T>(string query, string tblName) where T : DataSet, new()?很久没有求助于这些物品了。
  • 我们需要更多信息。我们需要知道您的型号。我们需要知道您为什么要在其中使用泛型。

标签: c# .net generics


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这对我很有效! “SQL 查询绝对可以是任何东西”是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
相关资源
最近更新 更多