SQL using 语句外的连接构造函数

SQL Connection constructor outside the using statement

我有以下代码:

SqlConnection Connect = new SqlConnection(IST_DBConnect.SQLConnectionString);
SqlCommand command = new SqlCommand(sqlCommandString, Connect);
RequestRow Result = new RequestRow();
Connect.Open();
using (Connect)
...

这不是我的代码,我会在 using 语句中编写 SQL 连接的创建,这是我朋友的代码,我不确定这是否会正确处理SQL 连接对象,如果在构造函数或 Open 方法中出现问题。所以我的问题是,如果创建了连接对象并且 open 方法抛出异常 => 永远不会打开连接,是否会正确处理?

谢谢。

来自 documentation;

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

根据您的示例,如果 Open 方法的构造函数出现问题,using 无法执行任何操作,因为您将其用作资源在您初始化之后。

当然这是最好的方法;

using(var Connect = new SqlConnection(IST_DBConnect.SQLConnectionString))
using(var command = Connect.CreateCommand())
{
   // 
} // <-- Both Connect and command will disposed here no matter exception is thrown or not