简体   繁体   English

退出方法时不使用而处置所有IDisposables?

[英]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. 也许我太懒了,但是在方法中using s嵌套会使该方法看起来复杂且难以理解。 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? 有什么方法可以使由于异常而在退出方法时自动释放在方法中创建的所有IDisposable对象?


PS. 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())
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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