Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当有多用途语句时,它们会按顺序执行吗?_C#_Dispose_Using_Using Statement - Fatal编程技术网

C# 当有多用途语句时,它们会按顺序执行吗?

C# 当有多用途语句时,它们会按顺序执行吗?,c#,dispose,using,using-statement,C#,Dispose,Using,Using Statement,比如说 using (Stream ftpStream = ftpResponse.GetResponseStream()) // a using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b { ........do something } 这两条语句a和b会按照我的顺序执行吗? 也以同样的顺序表示不满

比如说

  using (Stream ftpStream = ftpResponse.GetResponseStream())       // a             
  using (FileStream localFileStream = (new FileInfo(localFilePath)).Create()) // b
  {
                 ........do something
  }
这两条语句a和b会按照我的顺序执行吗? 也以同样的顺序表示不满


谢谢

它们将按文本顺序执行,并按相反顺序进行处理-因此将首先处理
localfilestream
,然后再处理
ftpStream

基本上,您的代码相当于:

using (Stream ftpStream = ...)
{
    using (FileStream localFileStream = ...)
    {
        // localFileStream will be disposed when leaving this block
    }
    // ftpStream will be disposed when leaving this block
}
using (Stream ftpStream = ftpResponse.GetResponseStream())
{
    using (FileStream localFileStream = (new FileInfo(localFilePath)).Create())
    {
        //insert your code here
    }
}
不过,这还不止于此。您的代码也与此等效(撇开不同类型的
localFileStream
):


是。此语法只是使用语句嵌套
的快捷方式或替代方式。您所要做的就是使用
语句省略第一个
上的括号。这相当于:

using (Stream ftpStream = ...)
{
    using (FileStream localFileStream = ...)
    {
        // localFileStream will be disposed when leaving this block
    }
    // ftpStream will be disposed when leaving this block
}
using (Stream ftpStream = ftpResponse.GetResponseStream())
{
    using (FileStream localFileStream = (new FileInfo(localFilePath)).Create())
    {
        //insert your code here
    }
}