将大括号放在与单行“if”的语句相同的行上是不好的形式。语句? [英] Would it be bad form to put braces on the same line as the statement for single line "if" statements?

查看:391
本文介绍了将大括号放在与单行“if”的语句相同的行上是不好的形式。语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道这是一个好习惯,总是包括大括号if,for等等,即使它们是可选的,如果只有一个下面的语句,因为它更容易意外做类似的事情:

So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:

if(something == true)
    DoSomething();
    DoSomethingElse();

这样的例子:

if(something == true)
{   DoSomething(); }

这样你仍然占用更少的行(IMO增加了可读性),但仍然不可能意外地从上面犯了错误?

That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?

我问,因为我不相信我曾经看过这种风格之前的if或循环,但我确实看到它用于getter和setter在C#属性如:

I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:

public string Name 
    {get;set;}

不要问什么是最好的,因为那太主观了,而只是这是否被认为是可接受的风格,如果不是,为什么不。

Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.

推荐答案

当我遇到一行if语句时,我通常跳过curlys并保持一切: / p>

When I come across a one-line if statement, I usually skip the curlys and keep everything on the same line:

if (something == true) DoSomething();

快速,方便,节省空间。

It's quick, easy, and saves space.

这篇关于将大括号放在与单行“if”的语句相同的行上是不好的形式。语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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