Dav*_*veB 43 c# using-statement
我今天正在浏览同事c#代码并发现以下内容:
using (MemoryStream data1 = new MemoryStream())
using (MemoryStream data2 = new MemoryStream())
{
// Lots of code..........
}
Run Code Online (Sandbox Code Playgroud)
我一直看到using声明后跟一对花括号,它们定义了对象生命的范围.我编写代码的同事说,data1 using语句的大括号不需要,代码做的就像它们存在并嵌套data2 using语句一样.那么,当花括号被省略时会发生什么?
Alb*_*nbo 103
是的,您也可以将它们放在一个using语句中:
using (MemoryStream data1 = new MemoryStream(),
data2 = new MemoryStream())
{
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
Chu*_*way 18
当您在一个for或一个if语句中省略花括号时,适用相同的规则.
顺便提一下,如果您反映到已编译的代码中,编译器反编译器会添加大括号.
JvR*_*JvR 18
从 C# 8 开始,您也可以不使用任何大括号使用此语法:
using var foo = new Foo();
var bar = foo.Bar();
Run Code Online (Sandbox Code Playgroud)
foo 然后将在其范围的末尾(通常在方法的末尾)进行处理 - 所以要注意在何处和何时使用。
参考 - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#example
Ste*_*hen 17
正是他所说的.上面的代码与编写完全相同:
using (MemoryStream data1 = new MemoryStream())
{
using (MemoryStream data2 = new MemoryStream())
{
// Lots of code
}
}
Run Code Online (Sandbox Code Playgroud)
只要在语句中只有一个命令,就可以在if/else/for/while/using/etc语句之后省略大括号.例子:
// Equivalent!
if (x==6)
str = "x is 6";
if(x == 6) {
str = "x is 6";
}
// Equivalent!
for (int x = 0; x < 10; ++x) z.doStuff();
for (int x = 0; x < 10; ++x) {
z.doStuff();
}
// NOT Equivalent! (The first one ONLY wraps the p = "bob";!)
if (x == 5)
p = "bob";
z.doStuff();
if (x == 5) {
p = "bob";
z.doStuff();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7931 次 |
| 最近记录: |