Skip to main content
 首页 » 编程设计

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

2024年02月23日16cloudgamer

这是我的代码:

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);  
}