0

我看到大量具有以下语法的代码片段

using (RandomType variable = new RandomType(1,2,3))
{
   // A bunch of code here.

}

为什么不直接声明变量并使用它呢?

这种 Using 语法似乎只会使代码混乱并使其可读性降低。如果它是如此重要以至于该变量仅在该范围内可用,为什么不将该块放在一个函数中呢?

4

6 回答 6

11

使用有一个非常明确的目的。

它设计用于实现 IDisposable 的类型。

在您的情况下,如果 RandomType 实现 IDisposable,它将在块的末尾获得 .Dispose()'d。

于 2009-03-17T14:01:45.347 回答
9
using (RandomType variable = new RandomType(1,2,3))
{
   // A bunch of code here.
}

与以下内容几乎相同(有一些细微差别):

RandomType variable = new RandomType(1,2,3);

try
{
    // A bunch of code
}
finally
{
    if(variable != null)
        variable.Dispose()
}

请注意,在调用“Using”时,您可以将任何内容转换为 IDisposable:

using(RandomType as IDisposable)

finally 中的 null 检查将捕获实际上未实现 IDisposable 的任何内容。

于 2009-03-17T14:01:26.033 回答
4

不,它不会弄乱你的代码,或者降低它的可读性。

using 语句只能用于 IDisposable 类型(即实现 IDisposable 的类型)。

通过在 using-block 中使用该类型,该类型的 Dispose 方法将在 using-block 的范围结束时使用。

所以,告诉我哪些代码对你来说可读性较差:

using( SomeType t = new SomeType() )
{
   // do some stuff
}

或者

SomeType t = new SomeType();

try
{
   // do some stuff
}
finally
{
   if( t != null ) 
   {
      t.Dispose();
   }
}
于 2009-03-17T14:02:34.517 回答
1

在 using 语句中使用的对象必须实现 IDisposable,因此在范围结束时,您可以保证 Dispose() 将被调用,因此理论上,您的对象应该在此时释放。在某些情况下,我发现它使我的代码更清晰。

于 2009-03-17T14:02:15.593 回答
1

using 关键字提供了一种确定性方式来清理对象分配的托管或非托管资源。如果您不使用 using 关键字,则您有责任在完成该对象后调用 Dispose()(或在某些情况下为 Close())。否则,资源可能直到下一次垃圾回收才会被清理,甚至根本不会被清理。

于 2009-03-17T14:03:54.247 回答
1

根据MSDN,以下using代码:

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

扩展为:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

它确实不会使您的代码混乱。其实恰恰相反!

于 2009-03-17T14:07:53.443 回答