use*_*301 3 c# using destruction unmanagedresources
using (Stuff1 stf1 = new Stuff1(...)) // Allocation of stf1
using (Stuff2 stf2 = new Stuff2(...)) // Allocation of stf2
{
try
{
// ... do stuff with stf1 and stf2 here ...
}
catch (Stuff1Exception ex1)
{
// ...
}
catch (Stuff2Exception ex2)
{
// ...
}
} // Automatic deterministic destruction through Dispose() for stf1/stf2 - but in which order?
Run Code Online (Sandbox Code Playgroud)
换句话说,是否保证首先调用stf2的Dispose()方法,然后保证stf1的Dispose()方法被调用为秒?(基本上:Dispose()方法是按照它们所属对象的分配顺序调用的吗?)
using语句与其他块级语句没有什么不同.如果您编写如下代码:
if (...)
if (...)
{
}
Run Code Online (Sandbox Code Playgroud)
你会清楚地知道发生了什么命令(不是我会建议那个特定的结构),因为它与此完全相同:
if (...)
{
if(...)
{
}
}
Run Code Online (Sandbox Code Playgroud)
所以它是using.您的代码与以下内容没有区别:
using (...)
{
using(...)
{
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,很明显内部使用块首先终止,因此它的资源应该首先处理.