在C#中使用using语句 [英] Using the using statement in C#

查看:324
本文介绍了在C#中使用using语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

什么是C#Using块,为什么要使用它?

我已经看到在代码块中间使用了using语句,这是什么原因?

I have seen the using statement used in the middle of a codeblock what is the reason for this?

推荐答案

使用语法可以(应该)用作为实现 IDisposable 。 using语句可确保在发生异常时调用Dispose。

The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.

    //the compiler will create a local variable 
    //which will go out of scope outside this context 
    using (FileStream fs = new FileStream(file, FileMode.Open))
    {
         //do stuff
    }

或者,您也可以使用:

    FileStream fs;
    try{
       fs = new FileStream();
       //do Stuff
    }
    finally{
        if(fs!=null)
           fs.Dispose();
    }

通过.NET Framework从MSDN额外读取

C#公共语言运行库(CLR),会自动释放用于存储不再需要的对象的内存。内存的释放是不确定的;每当CLR决定执行垃圾回收时,都会释放内存。但是,通常最好尽快释放有限的资源,例如文件句柄和网络连接。

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

using语句允许程序员指定何时使用资源的对象。应该释放它们。提供给using语句的对象必须实现IDisposable接口。此接口提供Dispose方法,该方法应释放对象的资源。

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

这篇关于在C#中使用using语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆