铸造类型IDisposable的 - 为什么? [英] Cast type to IDisposable - Why?
问题描述
看到这个。为什么显式转换为IDisposable的?这只是一个速记,保证了IDisposable被称为在退出using块?
使用(代理作为IDisposable接口)
{
字符串s = proxy.Stuff()
}
这个绝招,如果你能叫的话,很可能是因为代理
是一个类型,编译器无法验证真的器具的IDisposable
。
有关的好处在使用
指令是,如果参数是空
,然后的Dispose
没有通话将被在退出完成。在使用
语句的范围
所以,你所示的代码实际上是短期的手:
VAR一次性=代理为IDisposable的;
试
{
字符串s = proxy.Stuff();
}
终于
{
如果(一次性!= NULL)
disposable.Dispose();
}
在换句话说,它说:如果这个对象实现IDisposable,我需要当我用下面这段代码做处理它。
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()
}
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 implements IDisposable
.
The nice thing about the using
directive, is that if the parameter to it is null
, then no call to Dispose
will be done upon exiting the scope of the using
statement.
So the code you've shown is actually short-hand for:
var disposable = proxy as IDisposable;
try
{
string s = proxy.Stuff();
}
finally
{
if (disposable != null)
disposable.Dispose();
}
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."
这篇关于铸造类型IDisposable的 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!