如果一个对象在C#中实现了IDisposable
,那么可以编写以下代码:
using(DisposableFoo foo = new DisposableFoo())
我一直想知道为什么using
看起来像C#关键字,但需要在.Net框架中定义一个接口。在这个上下文中,using
是一个关键字(用于定义库导入),还是Microsoft在Visual Studio/.Net框架中重载了它的用法?我不会期望一个C#关键字依赖于一个库。
如果一个对象在C#中实现了IDisposable
,那么可以编写以下代码:
using(DisposableFoo foo = new DisposableFoo())
我一直想知道为什么using
看起来像C#关键字,但需要在.Net框架中定义一个接口。在这个上下文中,using
是一个关键字(用于定义库导入),还是Microsoft在Visual Studio/.Net框架中重载了它的用法?我不会期望一个C#关键字依赖于一个库。
这是一个关键字构造,需要一个IDisposable,因为它作用于对象的Dispose方法。让关键字使用类型也并不过分。例如if是一个关键字,需要一个条件(即Boolean)类型。
foreach
(使用IEnumerable
)和LINQ语法(在与LINQ to Objects一起使用时需要System.Linq
库)。int
和string
这样的关键字也依赖于框架中的类型System.Int32
和System.String
。C#与CLI紧密相关,语言规范使用最少的运行时特性。IDisposable用于"using"实际上非常严格,因为在大多数情况下(例如"foreach"、LINQ等),都支持具有和不具有特定运行时实现的支持。
然而,由于IDisposable/using结构对.NET至关重要,我怀疑即使是最小的(但合法的)CLI也无法在没有它的情况下进行,因此在语言规范中提到它并不是一个问题。
其他与特定类型相关的事项:
等等
我认为使用“使用”关键字可以使您的代码
B b=new B();//can get resource outside using statement but will dispose inside of it
using(A a=new A(),b,C c=new C() //A,B,C are variable of types that implement IDisposable){
SomeCode//Some code to execute
}
进入
B b= new B();
try{
A a= new A();
C c= new C();//B isn't here since
SomeCode//execute the code
}finallly{
a.Dispose();//The reason A,B,C need to implement IDisposable
b.Dispose();//is so the compiler can make sure that they can call Dispose()
c.Dispose();
}
为什么要使用IDisposable很重要,因为C#是强类型语言,在幕后它会调用Dispose(),实现IDisposable告诉编译器可以这样做。
类似于foreach与IEnumerable和IEnumerator的关系(调用GetEnumerator(),Current(),MoveNext(),尽管我认为它不仅适用于数组,而且适用于集合类)。
using
是C#关键字,用作处理IDisposable对象的语法糖。根据MSDN
using块定义了一个范围,在该范围之外,一个或多个对象将被处理。
使用using语句允许程序员指定使用资源的对象何时释放它们。提供给using语句的对象必须实现IDisposable接口。此接口提供Dispose方法,应该释放对象的资源。
令人惊讶的是,即使MSDN也没有明确说明这在幕后是如何发生的。它只说对象必须实现IDisposable接口,该接口在实现接口的对象上提供Dispose方法。因此,为了处理对象,它需要调用对象上的Dispose方法,以清理和释放对象使用的资源。
看一下这个例子...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
//Assume that Car is IDisposible.
using (Car myCar = new Car(1))
{
myCar.Run();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
//Declare myCar object with FullName of the type as seen in IL.
BlogSamples.Car myCar;
//Instantiate the object by calling the constructor, matching the flow of IL.
myCar = new Car(1);
try
{
myCar.Run();
}
finally
{
if(myCar != null)
myCar.Dispose();
}
}
}
}
http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%E2%80%98using%E2%80%99-block-in-c/
foreach
也是一个关键字,要求集合实现IEnumerable
接口。 - sepp2kforeach
使用鸭子类型 - http://blogs.msdn.com/b/kcwalina/archive/2007/07/18/ducknotation.aspx - thecoop