C# 实践 4 using 关键字

参考:

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/using-statement

"提供可确保正确使用 IDisposable 对象的方便语法。"

"using 语句可确保调用 Dispose,即使 using 块中发生异常也是如此。

通过将对象放入 try 块中,然后调用 finally 块中的 Dispose,可以实现相同的结果;实际上,这就是编译器转换 using 语句的方式。"

 using(XXX) {}

XXX 的作用域,在 {} 之中。

来自参考的示例代码:

var font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
{
    // use font2
}
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight();

  

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

// 外部不可用 font3, font4

  

原文地址:https://www.cnblogs.com/alexYuin/p/12404340.html