hev*_*ele 10 c# scope using curly-braces
我想知道为什么我们using在C#中使用语句.我查了一下,发现它用于执行语句然后清理对象.所以我的问题是:如果我们打开并关闭花括号({ })来定义范围,那不是一回事吗?
使用声明:
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...
}
}
Run Code Online (Sandbox Code Playgroud)
大括号:
{
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...
}
}
Run Code Online (Sandbox Code Playgroud)
两种方法之间是否存在显着差异?
好吧,使用(当且仅当类实现IDisposable接口时才合法)
using (SqlConnection conn = new SqlConnection(connString)) {
// Some Code
...
}
Run Code Online (Sandbox Code Playgroud)
等于这段代码
SqlConnection conn = null;
try {
SqlConnection conn = new SqlConnection(connString);
// Some Code
...
}
finally {
if (!Object.ReferenceEquals(null, conn))
conn.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)