你什么时候需要调用IDisposable接口,如果您正在使用语句中使用?如果您、什么时候、语句、接口

2023-09-04 12:45:59 作者:大 叔。

我在读另一个答案。它让我不知道,什么时候做一件需要,如果我使用using语句显式调用Dispose?

I was reading another answer. And it made me wonder, when do does one need to explicitly call Dispose if I am using using statements?

编辑:

只是为了从一个总的知识,没有什么表白我自己,我问的原因是因为有人在另一个线程说了一句暗示有一个很好的理由,必须手动调用Dispose ......所以我想,为什么不询问它...?

Just to vindicate myself from being a total know-nothing, the reason I asked was because someone on another thread said something implying there was a good reason to have to call Dispose manually... So I figured, why not ask about it...?

推荐答案

您不知道。该使用语句会为你。

You don't. The using statement does it for you.

根据 MSDN ,这code例如:

According to MSDN, this code example:

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

被扩展,在编译时,下面的code(注额外的花括号创建该对象的范围有限):

is expanded, when compiled, to the following code (note the extra curly braces to create the limited scope for the object):

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

注意:作为@timvw上述,如果​​您将方法或使用对象初始化using语句本身并抛出一个异常,该对象将不会被处理。这是有道理的,如果你看一下是什么将扩大到。例如:

Note: As @timvw mentioned, if you chain methods or use object initializers in the using statement itself and an exception is thrown, the object won't be disposed. Which makes sense if you look at what it will be expanded to. For example:

using(var cat = new Cat().AsDog())
{
   // Pretend a cat is a dog
}

扩展到

{
  var cat = new Cat().AsDog(); // Throws
  try
  {
    // Never reached
  }
  finally
  {
    if (cat != null)
      ((IDisposable)cat).Dispose();
  }
}    

AsDog 显然会抛出一个异常,因为猫永远不能作为真棒一只狗。猫然后将永远不会被处理。当然,有些人可能会说,猫不应该被处理掉,但这是另一个讨论...

AsDog will obviously throw an exception, since a cat can never be as awesome as a dog. The cat will then never be disposed of. Of course, some people may argue that cats should never be disposed of, but that's another discussion...

不管怎么说,只要确保你做什么使用(这里)是安全的,你是好去。 (显然,如果构造失败,该目标将不会被创建的开始,所以不需要设置)。

Anyways, just make sure that what you do using( here ) is safe and you are good to go. (Obviously, if the constructor fails, the object won't be created to begin with, so no need to dispose).