"using" 与 "dynamic" 一起阻止

"using" block together with "dynamic"

如果我写

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

这是否意味着当 using 块离开时调用 d.Dispose ()

d 没有实现 IDisposable 时会发生什么?

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

是的。如果该类型实现 IDisposable,则将调用 Dispose

What happens when d does not implement IDisposable?

你会得到一个例外

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?)

您可以通过 class 来自己尝试:

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

然后:

using (dynamic d = new MyDisposable())
{

}