gpt4 book ai didi

c# - 在 using 语句中抛出异常时,是否仍会调用 Dispose?

转载 作者:IT王子 更新时间:2023-10-29 03:37:33 24 4
gpt4 key购买 nike

在下面的示例中,如果在 using 语句中抛出异常,连接是否会关闭并释放?

using (var conn = new SqlConnection("..."))
{
conn.Open();
// stuff happens here and exception is thrown...
}

我知道下面的这段代码将确保它确实如此,但我很好奇 using 语句是如何做到的。

var conn;
try
{
conn = new SqlConnection("...");
conn.Open();
// stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
conn.Dispose();
}

相关:

What is the proper way to ensure a SQL connection is closed when an exception is thrown?

最佳答案

是的,using 将您的代码包装在一个 try/finally block 中,其中 finally 部分将调用 Dispose()(如果它存在)。但是,它不会直接调用 Close(),因为它只检查正在实现的 IDisposable 接口(interface)以及 Dispose() 方法.

另见:

关于c# - 在 using 语句中抛出异常时,是否仍会调用 Dispose?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/518352/

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