如果使用`using`语句,何时需要调用IDisposable? [英] When do you need to call IDisposable, if you are using `using` statements?

查看:43
本文介绍了如果使用`using`语句,何时需要调用IDisposable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读另一个答案.这让我想知道,如果我正在使用 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?

推荐答案

您没有. using 语句为您完成.

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

根据 MSDN ,此代码示例:

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

在编译时会扩展为以下代码(请注意为对象创建有限范围的多余花括号):

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();
  }
}


注意:作为


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).

这篇关于如果使用`using`语句,何时需要调用IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆