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
}
}