简体   繁体   中英

Dispose all IDisposables when exiting the method without using?

Perhaps I am too lazy, but nested using s in a method make the method look complicated and difficult to understand. Is there any way to make all IDisposable objects that were created in a method be automatically disposed when exiting the method due to an exception?


PS. Thank you for the feedback. I now know there is no such feature right now. But, theoretically, is the following hypothetical syntax plausible?

void SomeMethod()
{
     autodispose var com = new SQLCommand();
     ...
     autodispose var file = new FileStream();
     ....
     autodispose var something = CreateAnObjectInAMethod(); 
     ....
}

All three objects are automatically disposed when exiting the method for any reason.

No but you can tidy a bit like so...

This...

using (var conn = new SqlConnection("blah"))
{
    using (var cmd = new SqlCommand("blah"))
    {
        using (var dr = cmd.ExecuteReader())
        {

        }
    }
}

Becomes...

using (var conn = new SqlConnection("blah"))
using (var cmd = new SqlCommand("blah"))
using (var dr = cmd.ExecuteReader())
{

}

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