returning in the middle of a using block

后端 未结 7 1084
一生所求
一生所求 2020-11-27 15:08

Something like:

using (IDisposable disposable = GetSomeDisposable())
{
    //.....
    //......
    return Stg();
}

I believe it is not a p

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:25

    It's perfectly fine.

    You are apparently thinking that

    using (IDisposable disposable = GetSomeDisposable())
    {
        //.....
        //......
        return Stg();
    }
    

    is blindly translated into:

    IDisposable disposable = GetSomeDisposable()
    //.....
    //......
    return Stg();
    disposable.Dispose();
    

    Which, admittedly, would be a problem, and would make the using statement rather pointless --- which is why that's not what it does.

    The compiler makes sure that the object is disposed before control leaves the block -- regardless of how it leaves the block.

提交回复
热议问题