Cast type to IDisposable - Why?

后端 未结 3 1272
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 13:28

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 IDi         


        
3条回答
  •  攒了一身酷
    2020-12-31 13:52

    This could be required if you are given a proxy instance from somewhere and its static type does not implement IDisposable but you know that the real type may do and you want to make sure it will be disposed e.g.

    public class Proxy : ISomeInterface, IDisposable
    {
        ...
    }
    
    private ISomeInterface Create() { ... }
    
    ISomeInterface proxy = Create();
    
    //won't compile without `as`
    using(proxy as IDisposable)
    {
        ...
    }
    

提交回复
热议问题