c# - 如何为我的代码正确使用 "using"语句

标签 c# object idisposable using

这是我的代码:

Bitmap bmp = ImageManipulator.GetMyImageModified(bmp);
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);
tempBMP = ImageManipulator.CopyToBpp(tempBMP, 1);

string bmpFilename = String.Format("File{0}.png", indexNum);
tempBMP.Save(bmpFilename, ImageFormat.Png); 

现在我已经看到,对于 IDisposable 对象,最佳做法是使用 using 语句在不再需要这些对象时立即处置它们。 我想遵循这种做法,所以我需要一些帮助来重写上面的代码:

using (Bitmap bmp = ImageManipulator.GetMyImageModified(bmp){

   Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect); // bmp should be disposed after this line
   tempBMP = ImageManipulator.CopyToBpp(tempBMP, 1);

   string bmpFilename = String.Format("File{0}.png", indexNum);
   tempBMP.Save(bmpFilename, ImageFormat.Png); 
} // bmp is disposed here

这是我的第一次尝试,但它并不完美,因为 bmp 位图在不再需要时不会立即处理,尽管在这个特定示例中不应该强制这么快地处理它。

tempBitmap 问题更大,因为我无法在应该环绕的 using 语句中重新分配对新对象的引用:

Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);

确实 tempBMP 引用在用 using 关键字包围上面的行后变成了readonly

tempBMP 也被保存到一个文件中,保存操作应该是异步的,然后我不知道处置的影响:

tempBMP.Save(bmpFilename, ImageFormat.Png); 

接到电话。

如果您能帮助我编写更好的代码,我会洗耳恭听。

最佳答案

using (var sourceBmp = ...)
using (var modifiedBmp = ImageManipulator.GetMyImageModified(sourceBmp))
using (var croppedBmp = ImageManipulator.cropImage(modifiedBmp, rect))
using (var finalBmp = ImageManipulator.CopyToBpp(croppedBmp, 1))
{
    string bmpFilename = String.Format("File{0}.png", indexNum);
    finalBmp.Save(bmpFilename, ImageFormat.Png); 
}

关于c# - 如何为我的代码正确使用 "using"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462683/

相关文章:

javascript - 在Javascript中定义对象的属性数组

c# - 使用嵌套方法时奇怪的执行顺序,yield return 和组合使用

c# - 判断是否因为抛出异常而执行到 finally block 中

c# - EmguCV - 匹配模板

c# - 添加命名空间时出错

java - OOP - 通过实例类的引用变量访问对象

.net - 我是否应该在 HttpWebResponse 上调用 Close,即使它在 using 语句中?

c# - 十次 Thread.Sleep(100) 还是一次 Thread.Sleep(1000)?

c# - 框架类库(FCL) 是分别为C# 和C++ 实现的吗?

nhibernate - 如何从 CaSTLe ActiveRecord SessionScope 检索当前的 NHibernate Session 对象