什么时候应该使用using语句? [英] When should I use the using Statement?

查看:638
本文介绍了什么时候应该使用using语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

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

我将一个旧的网站到C#,我不知道什么时候我应该使用'使用'。是否有任何的一般准则?我所知道的好处,但我不是100%确定如何使用它。难道我每次'新'的方法/属性?

 的SqlConnection awesomeConn =新的SqlConnection(连接);
 

解决方案

如果一个类实现的IDisposable 那么它会创建一个需要处置的一些非托管资源当你使用它们完成。所以,你会做这样的事情:

 的SqlConnection awesomeConn =新的SqlConnection(连接);

//做一些东西

awesomeConn.Dispose();
 

要避免遗忘处置的源泉(在这种情况下,关闭数据库连接),特别是当一个异常被抛出,则可以使用使用语法来自动调用当你出去的using语句的范围内配置:

 使用(SqlConnection的awesomeConn =新的SqlConnection(连接))
{
     //做一些东西
} //自动执行.Dispose通话,就好像它是在一个finally块
 

事实上,使用块等效于:

 尝试
{
    SqlConnection的awesomeConn =新的SqlConnection(连接);

    //做一些东西
}
最后
{
    awesomeConn.Dispose();
}
 

Possible Duplicate:
What is the C# Using block and why should I use it?

I'm converting an old site to C# and I'm not sure when I should be using 'using'. Are there any general guidelines? I know of the benefits, but I'm not 100% sure how to use it. Is it every time I 'new' a method/property?

SqlConnection awesomeConn = new SqlConnection(connection);

解决方案

If a class implements IDisposable then it will create some unmanaged resources which need to be 'disposed' of when you are finished using them. So you would do something like:

SqlConnection awesomeConn = new SqlConnection(connection);

// Do some stuff

awesomeConn.Dispose();

To avoid forgetting to dispose of the resourses (in this case close the database connection), especially when an exception is thrown, you can use the using syntax to automatically call dispose when you go out of the using statement's scope:

using (SqlConnection awesomeConn = new SqlConnection(connection))
{
     // Do some stuff
} // automatically does the .Dispose call as if it was in a finally block

In fact, the using block is equivalent to:

try
{
    SqlConnection awesomeConn = new SqlConnection(connection);

    // do some stuff
}
finally 
{
    awesomeConn.Dispose();
}

这篇关于什么时候应该使用using语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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