C#switch语句有/无大括号....有什么区别? [英] C# Switch statement with/without curly brackets.... what's the difference?

查看:543
本文介绍了C#switch语句有/无大括号....有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的C#总是允许你省略花括号中的开关之间()语句内部情况:语句?



什么是省略他们的影响,因为JavaScript程序员经常做?



例如:

 开关(X)
{
情况下单向:
{//< ----这忽略整行
INT Y = 123;
FindYou(REF Y);
中断;
} //< ----这忽略整行
的情况下换另一支:
{//< ----这忽略整行
双Y = 456.7; //合法的!
GetchaGetcha(REF Y);
中断;
} //< ----这忽略整行
}


解决方案

花括号不是必需的,但他们可能会派上用场,以引入新的声明空间。这种行为,因为C#,据我所知1.0并没有改变。



忽略它们的效果是所有的变量声明的开关内部的某处语句是从他们在所有情况下的分支点报关可见



又见埃里克利珀的例子(案例3在后):




四开关古怪




Eric的例子:

 开关(X)
{
情况下单向:
INT Y = 123;
FindYou(REF Y);
中断;
的情况下换另一支:
双Y = 456.7; //非法!
GetchaGetcha(REF Y);
中断;
}

这不会编译,因为诠释是双Y 是由开关语句引入了相同的声明空间。

 开关(X)
{
:您可以通过分离用括号括起来的声明空间修复错误案例单向:
{
INT Y = 123;
FindYou(REF Y);
中断;
}
的情况下换另一支:
{
双Y = 456.7; //合法的!
GetchaGetcha(REF Y);
中断;
}
}


Has C# always permitted you to omit curly brackets inside a switch() statement between the case: statements?

What is the effect of omitting them, as javascript programmers often do?

Example:

switch(x)
{
  case OneWay:
  {                               //  <---- Omit this entire line
    int y = 123;
    FindYou(ref y);
    break;
  }                               //  <---- Omit this entire line
  case TheOther:
  {                               //  <---- Omit this entire line
    double y = 456.7; // legal!
    GetchaGetcha(ref y);
    break;
  }                               //  <---- Omit this entire line
}

解决方案

Curly braces are not required, but they might come in handy to introduce a new declaration space. This behavior hasn't changed since C# 1.0 as far as I know.

The effect of omitting them is that all variables declared somewhere inside the switch statement are visible from their point of declaration throughout all case branches.

See also Eric Lippert's example (case 3 in the post):

Four switch oddities

Eric's example:

switch(x)
{
  case OneWay:
    int y = 123;
    FindYou(ref y);
    break;
  case TheOther:
    double y = 456.7; // illegal!
    GetchaGetcha(ref y);
    break;
}

This does not compile because int y and double y are in the same declaration space introduced by the switch statement. You can fix the error by separating the declaration spaces using braces:

switch(x)
{
  case OneWay:
  {
    int y = 123;
    FindYou(ref y);
    break;
  }
  case TheOther:
  {
    double y = 456.7; // legal!
    GetchaGetcha(ref y);
    break;
  }
}

这篇关于C#switch语句有/无大括号....有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆