.NET/C# - 使用“using”处理对象陈述

发布于 2024-08-28 18:00:14 字数 322 浏览 3 评论 0原文

假设我有一个像这样的方法:

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

这仍然会处理“ms”对象吗?我有疑问,也许是因为在语句块完成之前返回了某些内容。

谢谢, 阿杰。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

本王不退位尔等都是臣 2024-09-04 18:00:14

是的。 using (x = e) { s }{ x = e; 的糖衣尝试 { s } 最后 { x.Dispose(); } }

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

放赐 2024-09-04 18:00:14

是的,使用会创建一个 try..finally 块,因此它会处理 ms (如果您将 ns 设置为 null,甚至会进行 null 检查)。

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

安静被遗忘 2024-09-04 18:00:14

是的,Using 语句背后的整个想法是它会自动处理您正在“使用”的任何流/对象。干得好。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文