将类型强制转换为 IDisposable - 为什么?
看到了这个。为什么显式转换为 IDisposable?这只是确保在退出 using 块时调用 IDisposable 的简写吗?
using (proxy as IDisposable)
{
string s = proxy.Stuff()
}
Saw this. Why the explicit cast to IDisposable? Is this just a shorthand to ensure that IDisposable is called on exiting the using block?
using (proxy as IDisposable)
{
string s = proxy.Stuff()
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个“技巧”(如果您可以这样称呼它)很可能是由于
proxy
的类型编译器无法验证是否真正实现了IDisposable
。using
指令的好处是,如果它的参数为null
,那么在退出时不会调用Dispose
using
语句的范围。因此,您所显示的代码实际上是以下内容的简写:
换句话说,它表示“如果该对象实现了 IDisposable,那么当我完成以下代码段时,我需要将其释放。”
This "trick", if you can call it that, is most likely due to
proxy
being of a type that the compiler can't verify really implementsIDisposable
.The nice thing about the
using
directive, is that if the parameter to it isnull
, then no call toDispose
will be done upon exiting the scope of theusing
statement.So the code you've shown is actually short-hand for:
In other words, it says "if this object implements IDisposable, I need to dispose of it when I'm done with the following piece of code."
如果您从某处获得一个
proxy
实例,并且其静态类型未实现IDisposable
,但您知道实际类型可能会实现,并且您想确保实现这一点,则可能需要这样做它将被处置,例如This could be required if you are given a
proxy
instance from somewhere and its static type does not implementIDisposable
but you know that the real type may do and you want to make sure it will be disposed e.g.这是不必要的,因为
using
语句显式绑定到IDisposable
接口,根据 MSDN 文档编辑:C# 语言规范(第 8.13 节)为
using
语句的语法糖提供了三种可能的扩展:注意,在每一个扩展中,无论如何都会完成强制转换,因此如最初所述,
as IDisposable
是不必要的。It's unnecessary as the
using
statement is explicitly tied to theIDisposable
interface, per the MSDN docsedit: The C# language spec (sec. 8.13) provides three possible expansions for the
using
statement's syntactic sugar:Note that in each one of these expansions the cast is done anyway, so as originally stated, the
as IDisposable
is unnecessary.