我如何使用“使用”为我的代码正确声明
这是我的代码:
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 位图在不再需要时不会立即处理,尽管在这个特定的情况下example 不应该强制让它如此快地得到处理。
tempBitmap 的问题更大,因为我无法将引用重新分配给应包围的 using 语句内的新对象:
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);
事实上,tempBMP 引用在包围后变为只读上面的行带有 using 关键字。
另外,tempBMP 会保存到文件中,并且保存操作应该是异步的,然后我不知道调用后立即处理的效果
tempBMP.Save(bmpFilename, ImageFormat.Png);
。
如果您能帮助我编写更好的代码,我会洗耳恭听。
This is my code:
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);
Now I've seen that for IDisposable objects is a best practice to use the using statement to dispose those object as soon as they are not needed anymore.
I want to follow this practise and so I need some help rewriting the above code:
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
This is my first attempt but it's not perfect cause the bmp Bitmap is non disposed as soon as not needed anymore though in this specific example shouldn't be mandatory to get it disposed so fast.
tempBitmap is more problematic because i cannot reassign the reference to a new Object inside the using statement that should surrond:
Bitmap tempBMP = ImageManipulator.cropImage(bmp, rect);
Indeed tempBMP reference becomes readonly after surrounding the above line with the using keyword.
Also tempBMP gets saved to a file and the Save operation should be asyncrhonous and then I don't know the effects of a dispose as soond as the:
tempBMP.Save(bmpFilename, ImageFormat.Png);
Get called.
If you can help me write better code, I'm all ears.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
using 关键字只是为了方便。显式调用 Dispose() 仍然是很有可能的。在finally 块中执行此操作。任意:
The using keyword is just a convenience. Calling Dispose() explicitly is still quite possible. Do so in a finally block. Arbitrarily: