Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在使用块或在使用块声明时声明IDisposable成员有什么区别?_C#_Dispose_Using Statement - Fatal编程技术网

C# 在使用块或在使用块声明时声明IDisposable成员有什么区别?

C# 在使用块或在使用块声明时声明IDisposable成员有什么区别?,c#,dispose,using-statement,C#,Dispose,Using Statement,我的代码如下: using (SqlCommand command = new SqlCommand()) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Connection = new SqlConnection(); command.CommandText = ""; command.Parameters.Ad

我的代码如下:

    using (SqlCommand command = new SqlCommand())
    {

        command.CommandType = System.Data.CommandType.StoredProcedure;
        command.Connection = new SqlConnection();
        command.CommandText = "";

        command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input);

        SqlDataReader dataReader = command.ExecuteReader();
   }
在声明SqlConnection时是否有任何功能上的影响,我目前正在声明它,而不是像这样声明它

using (SqlCommand command = new SqlCommand())
using (SqlConnection connection = new SqlConnection())

谢谢

是的,下面的代码将正确处理SqlConnection,而上面的代码不会。使用
块(内部实现为
try
finally
)的
确保无论您如何退出块,对象都将被释放。

是的,存在差异。处置
SqlCommand
不会自动处置与其关联的
SqlConnection
。您可以通过这种方式泄漏连接,这将干扰ADO.NET连接池;如果在代码运行时查看数据库服务器的活动,您将看到新的连接正在打开,而不是关闭


您应该始终使用第二个版本。实际上,
SqlConnection
对象是您真正需要处理的对象。您应该始终尽可能快地处置实现了
IDisposable
的任何东西,但未能处置
SqlConnection
尤其危险。

是的,最好使用2个使用块,每个资源1个

在这种情况下,您可以只使用1,但它应该围绕连接,而不是围绕命令


但你真的不想知道或关心这些细节。如果类实现IDispsoable接口,则在
using(){}
块中使用其实例,除非有特殊原因不这样做

我使用以下模式:

using(var connection = new SqlConnection("ConnectionName"))
using(var command = new SqlCommand())
{
   command.Connection = connection;
   // setup command
   var reader = command.ExecuteReader();
   // read from the reader
   reader.Close();
}