一次性使用模式 [英] Disposable Using Pattern

查看:117
本文介绍了一次性使用模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  using (FileStream fileStream = new FileStream(path))
  {
    // do something
  }

现在我所知道的使用模式是IDisposable接口的实现,即一个try / catch /最后的设置和调用Dispose的对象。我的问题是如何关闭的方法进行处理。

Now I know the using pattern is an implementation of IDisposable, namely that a Try/Catch/Finally is set up and Dispose is called on the object. My question is how the Close method is handled.

MSDN 说,它不叫,但我看过其他。

MSDN says that it is not called, but I have read otherwise.

我知道,从流中的FileStream inherrits这是解释的here 。既然说不会重写关闭(),因为它是由Dispose()方法调用。

I know that the FileStream inherrits from Stream which is explained here. Now that says not to override Close() because it is called by Dispose().

所以,做一些类只是调用close()在自己的Dispose()方法或不在使用调用close()?

So do some classes just call Close() in their Dispose() methods or does the using call Close()?

推荐答案

使用语句的的知道的Dispose(),但 Stream.Dispose 要求关闭(),因为在MSDN 记载:

The using statement only knows about Dispose(), but Stream.Dispose calls Close(), as documented in MSDN:

需要注意的是,由于落后
兼容性的要求,这种
方法的实现从$ b $不同,b表示$ b $建议指导b Dispose模式。此方法调用
关闭,然后调用
Stream.Dispose(布尔)。

Note that because of backward compatibility requirements, this method's implementation differs from the recommended guidance for the Dispose pattern. This method calls Close, which then calls Stream.Dispose(Boolean).

这篇关于一次性使用模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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