C# 中任意代码块(通过大括号)的实际用途是什么
我见过一个带有 switch 语句的示例,其中每个 case 块都被大括号包围,如下所示:
switch (itemType)
{
case ItemType.TV:
{
String message = Messages.GetMessage(itemType);
Console.WriteLine(message);
break;
}
case ItemType.Computer:
{
XPMessage message = XPMessage.Next();
if(message.Data == "XC12")
message.IsValid = true;
break;
}
case ItemType.WashingMachine:
{
String message = "Washing machines are so cool.";
Messages.SendMessage(message, itemType);
break;
}
default:
{
break;
}
}
我知道的唯一好处是限制声明范围(在示例中看到)。
但是,我想知道是否还有其他好的用途可以在这种代码块中分隔代码的某些部分(这里我的意思是不一定在 switch 语句中)。
何时以及如何使用它,如果不这样做 - 为什么不呢?
另外,使用此类代码块有什么缺点吗?
I have seen an example with the switch statement where each case block was surrounded by the curly brackets, like this:
switch (itemType)
{
case ItemType.TV:
{
String message = Messages.GetMessage(itemType);
Console.WriteLine(message);
break;
}
case ItemType.Computer:
{
XPMessage message = XPMessage.Next();
if(message.Data == "XC12")
message.IsValid = true;
break;
}
case ItemType.WashingMachine:
{
String message = "Washing machines are so cool.";
Messages.SendMessage(message, itemType);
break;
}
default:
{
break;
}
}
The only benefit I am aware of is limiting the declaration scope (seen in the example).
However, I'd like to know if there are any other good uses for separating some parts of the code in such kind of a code block (and here I mean not neccessarily within the switch statement).
When and how do you use it, and if you don't - why don't you?
Also, is there any downside to using such blocks of code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所说,声明范围是其中之一,也是可读性之一。有些人认为看到大括号比继续看到break语句要容易得多。这似乎是个人喜好。在本例中,这样做是为了确定范围,因为并非所有语句都使用相同的数据类型。
As you said declaration scope is one of them and also readability. Some people think it's much easier to see the braces rather than having to keep going until they see a break statement. It seems to be a personal preference. In this case it's done for scoping purposes because not all the statements use the same data type.
这只是一些人出于可读性/空白而喜欢的风格,而不是出于范围目的。
据我所知,没有其他好处。
It's just a stylistic thing that some people prefer for readability/white space, when not done for scope purposes.
There are no additional benefits that I am aware of.