gpt4 book ai didi

c# - "using"语句与花括号

转载 作者:可可西里 更新时间:2023-11-01 09:07:25 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com