在 using 块中创建资源与在 using 块外创建资源

Creating a resource in the using block vs outside the using block

例如,可以通过以下方式创建一次性资源的新实例:

var resource = CreateNewResource();

以下编码风格有什么区别(如果有的话)?

第一种风格:

var resource = CreateNewResource();
using (resource)
{
    //Use resource
}

第二种风格:

using (var resource = CreateNewResource())
{
    //Use resource
}

如果我们不打算在 using 块之外的任何地方使用资源,那么第一种样式是否是糟糕的编码实践?

即使我们希望使用using块之外的资源,这个希望是否应该在using块之外使用一次性资源受到鼓励?

第一个值得注意的区别是,在您的第一个代码段中,变量资源仍然在 using 块之后声明,因此有人可以在它被释放后使用它,这很糟糕。

var resource = CreateNewResource();
using (resource)
{
    //Use resource
}
...
// Unknowingly continues to use resource
resource.BadActOnDisposedObject();

如果你决定更自由地使用和分配你的资源,我建议使用 try/finally,像这样:

Resource resource = null;
try
{
    // do whatever
    resource = CreateNewResource();
    // continue to do whatever
}
finally
{
    if (resource != null)
    {
        resource.Dispose();
        resource = null;
    }
}

这保证您的资源在任何情况下都得到处理。

好的..所以这显然是一种不好的做法。

很好documented on MSDN:

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.

我在网上看到过这种风格。在我自己的代码中,每当样式 2 中的资源声明语句很长时,我将声明从 using(){} 中拉出,然后按照样式 1 中提到的代码编写代码,以提高代码的可读性。