我想知道为什么我们在 C# 中使用 using
语句。查了一下,发现是用来执行语句,然后清理对象的。所以我的问题是:如果我们打开和关闭大括号 ( { }
) 来定义范围,这不是一回事吗?
使用语句:
using (SqlConnection conn = new SqlConnection(connString)) {
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
// Do Something...
}
}
花括号:
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM Customers";
conn.Open();
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
// Do Something...
}
}
这两种方法有什么显着差异吗?
最佳答案
好吧,使用(当且仅当该类实现IDisposable
接口(interface)时才合法)
using (SqlConnection conn = new SqlConnection(connString)) {
// Some Code
...
}
等于这段代码
SqlConnection conn = null;
try {
SqlConnection conn = new SqlConnection(connString);
// Some Code
...
}
finally {
if (!Object.ReferenceEquals(null, conn))
conn.Dispose();
}
C# 不具有与 C++ 相同的行为,因此不要像在 C++ 中那样在 C# 中使用 {...} 模式:
{
SqlConnection conn = new SqlConnection(connString);
...
// Here at {...} block exit system's behavior is quite different:
//
// C++: conn destructor will be called,
// resources (db connection) will be safely freed
//
// C#: nothing will have happened!
// Sometimes later on (if only!) GC (garbage collector)
// will collect conn istance and free resources (db connection).
// So, in case of C#, we have a resource leak
}
关于c# - "using"语句与花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227852/