.NET/C# - Disposing an object with the 'using' statement

岁酱吖の 提交于 2019-12-09 16:11:53

问题


Suppose I have a method like so:

public byte[] GetThoseBytes()
{
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        ms.WriteByte(1);
        ms.WriteByte(2);
        return ms.ToArray();
    }
}

Would this still dispose the 'ms' object? I'm having doubts, maybe because something is returned before the statement block is finished.

Thanks, AJ.


回答1:


Yes. using (x = e) { s } is sugar for { x = e; try { s } finally { x.Dispose(); } }




回答2:


Yes, Using creates a try..finally block, so it disposes the ms (and even does a null check in case you set ns to null).




回答3:


Yes, the whole idea behind the Using statement is that it automatically disposes of whatever stream/object you are "using". nicely done.



来源:https://stackoverflow.com/questions/2641692/net-c-disposing-an-object-with-the-using-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!