gpt4 book ai didi

c# - 哪个版本的 using 语句是正确或最安全的?

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:12 24 4
gpt4 key购买 nike

下面的“使用”语句的版本 I 和 II 都有效,但我怀疑第一个版本仅有效,因为 Visual Studio 2010 中的 C# 垃圾收集器没有删除变量“上下文”( Entity Framework 变量)。另一方面,我从一个看似有信誉的来源从网上获得了第一个版本,所以我认为它可以吗?

版本一:

try
{
using ( AnEFEntity context = new AnEFEntity()) //note: no curly brackets!
using (var ts = new System.Transactions.TransactionScope())
{
// stuff here that uses variable context
}
}
catch (Exception ex)
{
}

//上面的编译和工作都很好——但是第一个'using'语句在范围内吗?似乎是这样,但它是可疑的。

版本二:
try
{

using ( AnEFEntity context = new AnEFEntity())
{ //note a curly bracket used for first ‘using’
using (var ts = new System.Transactions.TransactionScope())
{
// stuff here that uses variable context
}
} //note the placement of the second curly bracket for the first
}
catch (Exception ex)
{
}

//上面的编译也很好,工作正常——它比第一个版本更安全吗?

最佳答案

它对编译后的代码没有任何影响,因为外部 using 的主体声明只是内部 using陈述。就我个人而言,我通常更喜欢把大括号放进去,因为如果你想在外部 using 的开始之间引入更多代码,会更清楚发生了什么。声明和内部using陈述。但是,缩进也可以使这一点更清楚。您问题中的代码很难理解,因为它根本没有缩进,而我会使用如下两种格式:

using (...)
using (...)
{
// Body
}

对比
using (...)
{
using (...)
{
// Body
}
}

单大括号版本的风险在于您最终会意外地编写此代码:
using (...)
Log("Hello");
using (...)
{
// Body
}

那时,代码在执行流程方面不再符合您的要求。这通常会导致编译时错误,因为第二个 using语句通常取决于第一个声明的资源,但并非总是如此。

关于c# - 哪个版本的 using 语句是正确或最安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8103546/

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