为什么每个人都告诉我编写这样的代码是一种不好的做法?
if (foo)
Bar();
//or
for(int i = 0 i < count; i++)
Bar(i);
Run Code Online (Sandbox Code Playgroud)
省略花括号的最大理由是它有时可以是它们的两倍.例如,下面是一些为C#中的标签绘制发光效果的代码.
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
for (int x = 0; x <= GlowAmount; x++)
{
for (int y = 0; y <= GlowAmount; y++)
{
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
}
}
}
//versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
for (int x = 0; x <= GlowAmount; x++)
for (int y = 0; y <= GlowAmount; y++) …Run Code Online (Sandbox Code Playgroud) 真正想知道但从未发现的东西是PHP的快捷方式.
我目前正在编写一个带有foreach循环的函数,里面只有一个语句.我试图省略花括号,因为你可以在if/else控制结构中做,它可以工作.没有错误.
foreach($var as $value)
$arr[] = $value;
Run Code Online (Sandbox Code Playgroud)
现在我尝试以相同的方式使用它,但在其中放入一个if/else块.再次,工作,没有错误.
foreach($var as $value)
if(1 + 1 == 2) {
$arr[] = $value;
};
Run Code Online (Sandbox Code Playgroud)
然后,我想"为什么这有效?" 并省略了结束分号.还在工作.所以我尝试在foreach循环中使用if/else语句而没有花括号,并再次使用,仍然正常,没有错误.但是foreach循环现在真的关闭/结束了吗?
foreach($var as $value)
if(1 + 1 == 2)
$arr[] = $value;
Run Code Online (Sandbox Code Playgroud)
至少我再次省略了结束分号并且(正如预期的那样)发生了解析错误.
所以我的大问题是:我什么时候可以省略花括号和结构/循环/函数?我知道,我可以肯定地在这样做if和else.可是你知道while,for和foreach?
是的,我知道这是不是安全,智能,无论到代码,而无需花括号,并有像速记$condition ? true : false;和if: doSomething(); endif;,endfor;和endforeach;.我不想了解shorthands我只想了解有关何时何地可以省略大括号的条件.