Oma*_*eji 0 c# using-statement
我看到了大量带有以下语法的代码片段
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
Run Code Online (Sandbox Code Playgroud)
为什么不只是声明变量并使用它?
这种使用语法似乎只是使代码混乱并使其可读性降低.如果重要的是那个变量只在那个范围内可用,为什么不把这个块放在一个函数中呢?
Ree*_*sey 11
使用有一个非常明确的目的.
它设计用于实现IDisposable的类型.
在您的情况下,如果RandomType实现IDisposable,它将在块的末尾获得.Dispose().
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
Run Code Online (Sandbox Code Playgroud)
几乎是相同的(有一些微妙的差异):
RandomType variable = new RandomType(1,2,3);
try
{
// A bunch of code
}
finally
{
if(variable != null)
variable.Dispose()
}
Run Code Online (Sandbox Code Playgroud)
请注意,在调用"使用"时,您可以将任何内容转换为IDisposable:
using(RandomType as IDisposable)
Run Code Online (Sandbox Code Playgroud)
finally中的null检查将捕获任何实际上不实现IDisposable的内容.