Pau*_*ber 1 c# using-statement visual-studio
以下'using'语句的版本I和II都有效,但我怀疑第一个版本是否有效,因为Visual Studio 2010中的C#垃圾收集器尚未删除变量"context"(实体框架变量).另一方面,我从一个看似有信誉的来源网上获得了第一个版本,所以我认为它没关系?
版本I:
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)
{
}
Run Code Online (Sandbox Code Playgroud)
//以上编译很好并且工作正常 - 但是在范围内是第一个'使用'语句?似乎是这样,但它是可疑的.
版本II:
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)
{
}
Run Code Online (Sandbox Code Playgroud)
//以上也编译好并且工作正常 - 它比第一个版本更安全吗?
它对编译的代码完全没有区别,因为外部using语句的主体只是内部using语句.就个人而言,我通常更喜欢把括号括起来,因为如果你想在外部using语句的开头和内部using语句之间引入更多的代码,那么它会更清楚.但是,缩进也可以使这一点更加清晰.您的问题中的代码很难遵循,因为它根本没有缩进,而我会使用这样的两种格式:
using (...)
using (...)
{
// Body
}
Run Code Online (Sandbox Code Playgroud)
VS
using (...)
{
using (...)
{
// Body
}
}
Run Code Online (Sandbox Code Playgroud)
单支撑版本的风险是你最终意外写这个:
using (...)
Log("Hello");
using (...)
{
// Body
}
Run Code Online (Sandbox Code Playgroud)
此时,代码不再按照执行流程执行您想要的操作.这通常会导致编译时错误,因为第二个using语句通常依赖于第一个语句中声明的资源,但并非总是如此.
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |