使用“使用”语句C#感到困惑

时间:2010-10-26 08:11:53

标签: c# using named-scope

根据MSDN Library

using Statement (C# Reference)
Defines a scope, outside of which an object or objects will be disposed.

但我在这里发布了一些用户发布的代码,我对此感到困惑:(请参阅我对代码的评论)

using (OleDBConnection connection = new OleDBConnection(connectiongString))
           {
                if (connection.State != ConnectionState.Open)
                    connection.Open();
                string sql = "INSERT INTO Student (Id, Name) VALUES (@idParameter, @nameParameter)";

                using (OleDBCommand command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.CommandType = CommandType.Text;

                    OleDBParameter idParameter = command.CreateParameter();
                    idParameter.DbType = System.Int32;
                    idParameter.Direction = Parameterdirection.Input;
                    idParameter.Name = "@idParameter";
                    idParameter.Value = studentId; 

                    OleDBParameter nameParameter = command.CreateParameter();
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    finally
                    {
                        // Is it still necessary to dispose these objects here?
                        command.Dispose();
                        connection.Dispose();
                    }
                }
            }

在上面的代码中,using语句是否正确使用? 我很困惑,任何人都可以解释如何使用using语句及其范围以及何时,何地以及为何使用它。谢谢..

2 个答案:

答案 0 :(得分:11)

finally块(因此在这种情况下为try)是多余的,这是using所做的,它在Dispose对象上调用IDisposableusing块结束时(无论例外情况或缺少例外情况),它都会被初始化。

答案 1 :(得分:11)

using语句是手动放置try/finally块的简写。

所以

using( x ){
  ...
}

相同
try{
  ...
}finally{
  if( x != null ){ x.Dispose(); }
}

他们将在编译时生成相同的IL。

如果x未实现IDisposable,编译器会给您一个错误。

相关问题