为什么类实现IDisposable显式而不是隐式? [英] Why would a class implement IDisposable explicitly instead of implicitly?

查看:151
本文介绍了为什么类实现IDisposable显式而不是隐式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 FtpWebResponse 类,没有看到处理方法。 事实证明该类实现了IDisposable,但是明确地这样做,以便在调用Dispose之前必须首先将您的实例转换为IDisposable:

I was using the FtpWebResponse class and didn't see a Dispose method. It turns out that the class implements IDisposable, but does so explicitly so that you must first cast your instance to IDisposable before calling Dispose:

// response is an instance of FtpWebResposne
((IDisposable) response).Dispose();

为什么这样的类的设计者会选择明确地实现IDisposable?作为安东尼Pegram说,这样做的事情掩盖了这样一个事实,即对于每次使用课程时不会查阅文档的平均开发人员,该对象应该被处理。

Why would the designer of a class such as this one choose to implement IDisposable explicitly? As Anthony Pegram says, doing things this way masks the fact that the object should be disposed for the average developer who is not consulting the documentation every time he/she uses a class.

推荐答案

通常情况下,如果该类具有与完全相同的关闭方法,处置。原来的 Dispose 隐藏在显式实现中,所以完全相同的方法没有两个名称。

This is normally done if the class has a Close method that is the exact same as Dispose. The original Dispose is hidden in an explicit implementation so that the exact same method doesn't have two names.

这里正式推荐:

如果这样的术语是标准的,例如与文件或套接字一样,请执行一个清除目的的Close方法。当这样做时,建议您将关闭实现与Dispose ... 相同

请考虑实现接口成员以隐藏成员并添加一个名称更好的等效成员。

有时域名的名称比Dispose更合适。例如,文件封装可能需要使用方法名称Close。在这种情况下,实施Dispose私有并创建一个调用Dispose的公共Close方法。

(PS我不同意这个约定。)

(P.S. I disagree with this convention.)

这篇关于为什么类实现IDisposable显式而不是隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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