在 using 语句中创建一个实例,确保退出 using 语句时在对象上调用 Dispose。当到达 using 语句的末尾,或者如果在语句结束之前引发异常并且控制离开语句块,都可以退出 using 语句。
实例化的对象必须实现 System.IDisposable 接口。示例// cs_using_statement.cs// compile with /reference:System.Drawing.dllusing System.Drawing;class a{ public static void Main() { using (Font MyFont = new Font("Arial", 10.0f), MyFont2 = new Font("Arial", 10.0f)) { // use MyFont and MyFont2 } // compiler will call Dispose on MyFont and MyFont2Font MyFont3 = new Font("Arial", 10.0f);
using (MyFont3) { // use MyFont3 } // compiler will call Dispose on MyFont3}
}