【发布时间】:2010-10-26 08:11:53
【问题描述】:
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 语句及其范围以及何时、何地以及为什么使用它。谢谢。。
【问题讨论】:
标签: c# using named-scope