我正确使用"使用"声明吗?

Tra*_*y13 2 .net c# using-statement

我想知道我的使用using是否正确.在using统计中,我决定是否应该在游戏中使用图像.

Image imageOfEnemy;
using(imageOfEnemy=Bitmap.FromFile(path))
{
   // some stuff with the imageOfEnemy variable

}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,我现在不需要打电话Dispose.

Dar*_*rov 9

是的,您正确使用它.您不需要显式处理Bitmap,因为它将由using语句处理.您可以通过在内部声明图像变量来进一步简化:

using(var imageOfEnemy = Bitmap.FromFile(path))
{
    // some stuff with the imageOfEnemy variable
}
Run Code Online (Sandbox Code Playgroud)

这大致相当于:

{
    var imageOfEnemy = Bitmap.FromFile(path);
    try 
    {
        // some stuff with the imageOfEnemy variable
    }
    finally 
    {
        ((IDisposable)imageOfEnemy).Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这甚至不是更简单但更安全:您确定在使用块之后不使用已处置的对象. (3认同)