使用“使用”感到困惑语句 C#
using 语句(C# 参考)
定义一个范围,在该范围之外将处理一个或多个对象。
但是我得到了一些用户在此处发布的代码,我对此感到困惑:(请参阅我对代码的评论)
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
语句及其范围以及何时、何地以及为何使用它。谢谢..
According to MSDN Library
using Statement (C# Reference)
Defines a scope, outside of which an object or objects will be disposed.
But I got this code posted here by some user and I got confused about this: (please see my comment on the code)
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();
}
}
}
In the above code, does the using
statement properly used?
I'm confused, can anyone please explain how to use using
statement and its scoping and when, where and why to use it. Thank you..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
using 语句是手动放置
try/finally
块的简写。所以
是一样的
并且它们在编译时会生成相同的 IL。
如果
x
未实现IDisposable
,编译器将给出错误。The using statement is a shorthand for manually putting a
try/finally
block.So
Is the same as
And they will generate the same IL when compiled.
The compiler will give you an error in case
x
does not implementIDisposable
.finally
块(因此在本例中为try
)是多余的,这就是using
的作用,它调用Dispose
> 在IDisposable
对象上,当using
块结束时使用该对象进行初始化(无论是否存在异常)。The
finally
block (and thus in this case thetry
) is redundant, that's whatusing
does, it callsDispose
on theIDisposable
object with which it is initialized when theusing
block ends (regardless of exceptions or lack thereof).