作者:mobiledu2502897273 | 来源:互联网 | 2022-11-23 18:22
1> Dmitry Byche..:
我们通常会将其包裹 IDisposable
起来using
,以保证实例(即非托管资源)将被暴露在风雨中.如果要在内部循环Image
之外声明:
for (int i = 0; i <10; i++)
{
using (Image imgInput = new Image())
{
for (int j = 0; j <100; j++)
{
...
// In all these cases the resource will be correctly released:
if (someCondition1)
break;
...
if (someCondition2)
return;
...
if (someCondition3)
throw new SomeException(...);
...
// Here is a code to use my image
}
}
}
这就是为什么我们不应该Dispose
明确地打电话.请注意, 您提供的两个代码摘录都会导致资源泄漏,如果是someCondition2
或someCondition3
.
如果要Image
在嵌套循环中声明,请使用相同的方案:
for (int i = 0; i <10; i++)
{
for (int j = 0; j <100; j++)
{
using (Image imgInput = new Image())
{
// Here is a code to use my image
}
}
}