简体   繁体   中英

“using” block together with “dynamic”

If I write

using (dynamic d = getSomeD ()) {
   // ...
}

does that mean that d.Dispose () is called when the using block is left?

What happens when d does not implement IDisposable ?

does that mean that d.Dispose () is called when the using block is left?

Yes. If the type implements IDisposable then Dispose will be called.

What happens when d does not implement IDisposable?

You will get an exception

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
Cannot implicitly convert type 'YourType' to 'System.IDisposable'. An explicit conversion exists (are you missing a cast?)

You can try that yourself by having a class like:

class MyDisposable : IDisposable //Remove IDisposable to see the exception
{
    public void Dispose()
    {
        Console.WriteLine("Dispose called");
    }
}

and then:

using (dynamic d = new MyDisposable())
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM