当有多个using语句时,它们会按顺序执行吗?

发布于 2024-10-03 18:20:40 字数 305 浏览 0 评论 0原文

例如,

  using (Stream ftpStream = ftpResponse.GetResponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }

两个语句 a 和 b 会按照我输入的顺序执行吗? 并以相同的顺序丢弃?

谢谢

for example

  using (Stream ftpStream = ftpResponse.GetResponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }

will the two statement a and b executed in the order i put?
and displose in the same order as well??

Thanks

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

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

发布评论

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

评论(2

阳光的暖冬 2024-10-10 18:20:40

它们将以文本顺序执行,并以相反的顺序进行处理 - 因此,localFileSream 将首先被处理,然后是 ftpStream

基本上你的代码相当于:

using (Stream ftpStream = ...)
{
    using (FileStream localFileStream = ...)
    {
        // localFileStream will be disposed when leaving this block
    }
    // ftpStream will be disposed when leaving this block
}

但它比这更进一步。您的代码与此等效(不考虑不同类型的localFileStream):

using (Stream ftpStream = ..., localFileStream = ...)
{
    ...
}

They will execute in textual order, and be disposed in reverse order - so localFileSream will be disposed first, then ftpStream.

Basically your code is equivalent to:

using (Stream ftpStream = ...)
{
    using (FileStream localFileStream = ...)
    {
        // localFileStream will be disposed when leaving this block
    }
    // ftpStream will be disposed when leaving this block
}

It goes further than that though. Your code is also equivalent (leaving aside the different type of localFileStream) to this:

using (Stream ftpStream = ..., localFileStream = ...)
{
    ...
}
始于初秋 2024-10-10 18:20:40

是的。此语法只是嵌套 using 语句的快捷方式或替代方式。您所做的只是省略第一个 using 语句中的括号。它相当于:

using (Stream ftpStream = ftpResponse.GetResponseStream())
{
    using (FileStream localFileStream = (new FileInfo(localFilePath)).Create())
    {
        //insert your code here
    }
}

Yes. This syntax is just a shortcut or alternative way of nesting using statements. All you're doing is omitting the brackets on the first using statement. It's equivalent to:

using (Stream ftpStream = ftpResponse.GetResponseStream())
{
    using (FileStream localFileStream = (new FileInfo(localFilePath)).Create())
    {
        //insert your code here
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文