显式实现了IDisposable的 [英] Explicit implementation of IDisposable

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

问题描述

虽然有相当多的Q&放大器;至于关于的IDisposable 要在SO发现,我还没有找到一个答案尚未:

Although there are quite a lot of Q&As regarding IDisposable to be found on SO, I haven't found an answer to this yet:

我通常遵循的做法是,当我的一个类拥有一个的IDisposable 对象,然后它还要实现的IDisposable 和所拥有的对象上调用处置。但是最近我遇到了一个类,它实现的IDisposable 明确因此$ P $的直接调用pventing我处置迫使我投它,我发现恼人的和不必要的。

I usually follow the practice that when one of my classes owns an IDisposable object then it also implements IDisposable and calls Dispose on the owned object. However recently I came across a class which implemented IDisposable explicitly thus preventing me from directly calling Dispose forcing me to cast it which I found annoying and unnecessary.

所以,问题:为什么以及何时总会有需要使用的IDisposable 的显式接口实现?我知道,有非常好的有效的理由明确实现一个接口,但在关于的IDisposable 的原因不是很清楚我的。

So the question: Why and when would one want to use an explicit interface implementation of IDisposable? I know that there are perfectly good and valid reason for implementing an interface explicitly but in regards to IDisposable the reason is not quite clear to me.

推荐答案

我会说这是不寻常有一个明确的实施 IDisposable.Dispose ,除非你有一个备用等效方法(如关闭)。

I'd say it's unusual to have an explicit implementation of IDisposable.Dispose unless you have an alternate equivalent method (e.g. Close).

在这种情况下,你的包装类可以调用关闭,而不是铸造。

In which case your wrapper class could call Close rather than casting.

一个例子是 WebResponse类类的框架和LT = V3.5。有趣的是存在于.NET 4的公开Dispose方法,也许微软已经决定,明确实施可能不是很好的做法。

An example is the WebResponse class in the Framework <= V3.5. Interestingly there is a public Dispose method in .NET 4, so maybe Microsoft has now decided that an explicit implementation may not be good practice.

肖恩·法卡斯,设计工程师在CLR安全团队中写道 MSDN杂志

Shawn Farkas, a design engineer on the CLR security team writes in MSDN magazine that

虽然使用块将与那些具有明确的IDisposable实现类,我建议阶级是不会实现的接口这种方式。如果你明确地实现IDisposable,谁正在探索在VisualStudio®的使用的IntelliSense®对象模型的开发人员不会注意到对象具有Dispose方法

Although the using block will work with classes that do have an explicit IDisposable implementation, I recommend that classes never implement the interface this way. If you explicitly implement IDisposable, developers who are exploring your object model using IntelliSense® in Visual Studio® will not notice that the object has a Dispose method

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

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