铸造类型IDisposable的 - 为什么? [英] Cast type to IDisposable - Why?

查看:133
本文介绍了铸造类型IDisposable的 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到这个。为什么显式转换为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屋!

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