yon*_*236 12 c# named-scope using
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,using语句是否正确使用?我很困惑,任何人都可以解释如何使用using语句及其范围以及何时,何地以及为何使用它.谢谢..
Mot*_*tti 11
的finally(在这种情况下,因此块try)是冗余的,这就是using做,它调用Dispose在上IDisposable与它被初始化对象的时候,using块结束(无论异常或缺乏它们).
Øyv*_*hen 11
using语句是手动放置try/finally块的简写.
所以
using( x ){
...
}
Run Code Online (Sandbox Code Playgroud)
是相同的
try{
...
}finally{
if( x != null ){ x.Dispose(); }
}
Run Code Online (Sandbox Code Playgroud)
并且它们将在编译时生成相同的IL.
如果x没有实现,编译器会给你一个错误IDisposable.