为什么类实现IDisposable显式而不是隐式?

编程入门 行业动态 更新时间:2024-10-09 03:21:14
本文介绍了为什么类实现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显式而不是隐式?

本文发布于:2023-11-23 13:18:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   隐式   IDisposable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!