我想知道为什么我们在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/