pli*_*nth 312
如果类型实现了IDisposable,它会自动处理它.
鉴于:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
Run Code Online (Sandbox Code Playgroud)
这些是等价的:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
Run Code Online (Sandbox Code Playgroud)
第二个更容易阅读和维护.
Sam*_*Sam 105
UsingDispose()在using-block被保留之后调用,即使代码抛出异常.
所以你通常using用于需要在它们之后进行清理的类,比如IO.
所以,这个使用块:
using (MyClass mine = new MyClass())
{
mine.Action();
}
Run Code Online (Sandbox Code Playgroud)
会做同样的事情:
MyClass mine = new MyClass();
try
{
mine.Action();
}
finally
{
if (mine != null)
mine.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
使用using更简短,更容易阅读.
Rob*_* S. 41
来自MSDN:
C#通过.NET Framework公共语言运行库(CLR)自动释放用于存储不再需要的对象的内存.记忆的释放是不确定的; 只要CLR决定执行垃圾收集,就会释放内存.但是,通常最好尽快释放文件句柄和网络连接等有限资源.
using语句允许程序员指定何时使用资源的对象应该释放它们.提供给using语句的对象必须实现IDisposable接口.此接口提供Dispose方法,该方法应释放对象的资源.
换句话说,该using语句告诉.NET在using不再需要块时释放块中指定的对象.
小智 26
using语句用于处理实现IDisposable接口的C#中的对象.
该IDisposable接口有一个名为的公共方法Dispose,用于处理该对象.当我们使用using语句时,我们不需要在代码中显式地处理对象,using语句会处理它.
using (SqlConnection conn = new SqlConnection())
{
}
Run Code Online (Sandbox Code Playgroud)
当我们使用上面的块时,内部代码生成如下:
SqlConnection conn = new SqlConnection()
try
{
}
finally
{
// calls the dispose method of the conn object
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请阅读:了解C#中的"using"语句.
using (B a = new B())
{
DoSomethingWith(a);
}
Run Code Online (Sandbox Code Playgroud)
相当于
B a = new B();
try
{
DoSomethingWith(a);
}
finally
{
((IDisposable)a).Dispose();
}
Run Code Online (Sandbox Code Playgroud)