该
using语句的原因是要确保对象在超出范围后立即被处置,并且不需要显式代码即可确保这种情况发生。
与
理解C#(preproject)中的’using’语句 和
使用实现IDisposable的对象(microsoft)中一样 ,C#编译器将转换
using (MyResource myRes = new MyResource()){ myRes.DoSomething();}至
{ // Limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes != null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); }}C#8引入了一种新语法,名为“ using Declarations ”:
using声明是在using关键字之后的变量声明。它告诉编译器声明的变量应放在封闭范围的末尾。
因此,上述等效代码为:
using var myRes = new MyResource();myRes.DoSomething();
当控件离开包含范围(通常是一种方法,但也可以是代码块)时,
myRes将被处置。



