C# 允许我执行以下操作(来自 MSDN 的示例):
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
如果 font4 = new Font
抛出会发生什么?据我了解,font3 会泄漏资源并且不会被处理掉。
- 这是真的吗? (font4 不会被丢弃)
- 这是否意味着应该完全避免
using(... , ...)
以支持嵌套使用?
最佳答案
没有。
编译器将为每个变量生成一个单独的 finally
block 。
spec (§8.13) 说:
When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A
using
statement of the formusing (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement
is precisely equivalent to a sequence of nested using statements:
using (ResourceType r1 = e1) using (ResourceType r2 = e2) ... using (ResourceType rN = eN) statement
关于c# - 具有多个资源的 "using"会导致资源泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118201/