使用返回DataTable的方法

时间:2011-05-03 09:44:15

标签: c# datatable idisposable

考虑以下示例:

public static DataTable GetDataTable()
{
    using(DataTable dt = new DataTable())
    {
        // fill DataTable logic
        return dt;
    }
}

public void main()
{
    DataTable dt = GetDataTable();

    // contine using dt
}

我应该期望dt可以使用main(),还是DataTable处理GetDataTable()

4 个答案:

答案 0 :(得分:7)

是的,DataTable阻止using阻止GetDataTable

答案 1 :(得分:5)

是的,当代码退出using范围时,DataTable将被处理。

您应该将using移至main()

public static DataTable GetDataTable()
{
    DataTable dt = new DataTable()

    // fill DataTable logic
    return dt;
}

public void main()
{
  using(DataTable dt = GetDataTable())
  {
  // contine using dt
  }//here the table is disposed
}

答案 2 :(得分:2)

你必须替换

public  void main()

public static void Main()

public static DataTable GetDataTable()
{
  using(DataTable dt = new DataTable())
  {
    // fill DataTable logic
    return dt;
  }
}

一旦您的代码离开,GetDataTable dt将被处理掉。因为using调用IDisposible

答案 3 :(得分:0)

    public DataTable GetValue(string name)
    {
        string connection = @"Data Source=DESKTOP-M5TQV9A;Initial Catalog=ALLTEST;Integrated Security=True";
        DataTable dt;
        SqlConnection con = new SqlConnection(connection);
        con.Open();
        using (SqlCommand cmd = new SqlCommand("up_searchUsers", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@SearchName", SqlDbType.VarChar).Value = name;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            con.Close();
            return dt;
        }
    }

在文本框中搜索,然后获得结果! :)快乐C#Codding

dataGridView1.DataSource = GetValue(textBox1.Text);