使用使用说明书在C#中 [英] Using the using statment in c#

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it\">What在C#中使用块我为什么要使用它呢?

我见过using语句在$ C $一个cblock中间使用究竟是什么原因呢?

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
    }

另外,你可以只使用:

Alternatively you could just use:

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

从MSDN 额外读

C#通过.NET Framework公共语言运行时(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#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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