我正在使用FtpWebResponse类,但没有看到Dispose方法。 It turns out,该类实现了IDisposable,但是明确地做到了这一点,因此您必须先将实例转换为IDisposable,然后再调用Dispose:

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

这样的一类的设计者为什么会选择显式实现IDisposable?与Anthony Pegram says一样,以这种方式进行操作掩盖了以下事实:应将对象分配给一般开发人员,而这些开发人员每次使用类时都不会查阅文档。

最佳答案

如果类具有与Close完全相同的Dispose方法,通常可以完成此操作。原始的Dispose隐藏在显式实现中,因此完全相同的方法没有两个名称。

在这里正式推荐:

Do implement a Close method for cleanup purposes if such terminology is standard, for example as with a file or socket. When doing so, it is recommended that you make the Close implementation identical to Dispose...

Consider implementing interface members explicitly to hide a member and add an equivalent member with a better name.

Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose.

(P.S.我不同意这个惯例。)

10-05 20:29