有没有办法制作一个“使用”?语句在嵌套语句之前终止?
当一个字段用于创建另一个字段,然后进行处置时 – 我看到两个选项。第一:
Image image = Image.FromFile(path);
Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr());
image.Dispose();//not needed anymore.
//use bitmap
bitmap.Dispose();
第二:
using (Image image = Image.FromFile(path))
{
using (Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr()))
{
//use bitmap
}
}
逻辑上的第一个(因为使用Bitmap
时不需要Image
),但是using
语句通常比 Dispose
更可取。
是否有第三种方法 - 在第二个方法中使用 using
终止第一个方法?
When a field is used for creating another field, and then disposed – I see two options. First:
Image image = Image.FromFile(path);
Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr());
image.Dispose();//not needed anymore.
//use bitmap
bitmap.Dispose();
Second:
using (Image image = Image.FromFile(path))
{
using (Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr()))
{
//use bitmap
}
}
The logical one would be the first (because the Image
isn’t needed when the Bitmap
is used), but using
statements are generally preferable over Dispose
.
Is there a third way – to terminate the first using
inside the second one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,有:将生成缩略图的代码放入方法中:
请注意:
我同意奥德的评论。我使用这段代码不是因为它首先处理
image
,而是因为它更具可读性。Yes, there is: Put the code to produce the thumbnail image into a method:
Please note:
I agree with Oded's comments. I would use this code not because it disposes
image
first, but because it is more readable.创建一个工厂来生成您自己的图像:假设它是 MyImage,因此 MyImage 必须实现 IDisposable 接口。创建一个将根据您的规则生成图像的工厂后,使用您自己的图像:MyImage。
Make a factory which will generate your own image : let's say it MyImage so MyImage must implements the IDisposable interface. After make a factory which will generate the images based on your rules use the using over you own image : MyImage.