多使用块C#

2023-09-05 03:32:09 作者:櫻桃小丸子

我工作的应用程序中,我需要访问数据库。使用using语句是一件好事,因为使用语句,以确保对象总是正确处置,并且它不要求明确code,以确保这种情况的发生。让我有点困惑,其中使用,并在那里用不。

 公众诠释路线(路线R)
{
    尝试
    {
        使用(SqlConnection的CON =新的SqlConnection(的connectionString))
        {
            使用(SqlCommand的COM =新的SqlCommand(,CON))
            {
                使用(SqlDataReader的SDR = com.ExecuteReader())
                {
                }
            }
        }
    }
    赶上(例外五)
    {
    }
}
 

解决方案

任何时候你创建工具对象的IDisposable ,处理它(使用或不使用使用语法糖)是个好主意。

使用块语法糖(超过说明书 .Dispose()电话)是的Dispose()将still被称为即使有一个例外,流离开using块。

另外请注意,你可以堆叠起来的usings,没有嵌套缩进:

 使用(SqlConnection的CON =新的SqlConnection(的connectionString))
使用(SqlCommand的COM =新的SqlCommand(,CON))
使用(SqlDataReader的SDR = com.ExecuteReader())//仍然需要打开连接...
{
   ...
 

顺便说一句,进一步的使用效益是,如果的IDisposable 变量是在使用,它的变量是只读,不能块内重新分配,例如:

 使用(SqlDataReader的SDR = com.ExecuteReader())
{
   特别提款权=新SqlDataReader的()//错误
 
C 的程序结构

I am working on application in which i need to access database. Use of using statement is good because "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens. So i am little bit confused where to use "using" and where to not.

public int route(Route r)
{
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using(SqlCommand com = new SqlCommand("",con))
            {
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                }
            }
        }
    }
    catch (Exception e)
    {
    }
}

解决方案

Any time an object you create implements IDisposable, disposing of it (with or without the using syntactic sugar) is a good idea.

The benefit of the using block syntactic sugar (over manual .Dispose() calls) is that Dispose() will still be called even if there is an exception and flow leaves the using block.

Also, note that you can stack up the usings, without nested indentation:

using (SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
   ...

As an aside, a further benefit of using is that if the IDisposable variable is declared within the using, it that the variable is readonly and cannot be reassigned within the block, e.g.:

using (SqlDataReader sdr = com.ExecuteReader())
{
   sdr = new SqlDataReader() // Error

相关推荐