有时我自己编写的代码需要多层 if/else 语句相互合并(示例如下)。
我想知道是否可以缩短一点,因为有时我有超过 70 行代码的 if/else 语句树,老实说,与看起来多余的行相比,它们填得太多了。
这是一个示例代码:
if (labelGiveTip1.Visible == true)
{
if (labelGiveTip2.Visible == true)
{
labelGiveTip3.Visible = true;
if (labelGiveTip3.Visible == true)
{
Custom_DialogBox.Show("All of your hints for this assignment is used, do you want annother assignmment?", //main text argument
"Error: No more hints", //header argument
"Back", //first button text argument
"Get a new assignment"); //second button text argument
//this is a custom dialog box
result = Custom_DialogBox.result;
switch (result)
{
case DialogResult.Yes:
buttonNextAssignment.PerformClick();
break;
case DialogResult.Cancel:
break;
default:
break;
}
}
}
else
{
labelGiveTip2.Visible = true;
}
}
else
{
labelGiveTip1.Visible = true;
}
最佳答案
在我的代码中,我倾向于首先检查错误条件并尽快返回。多年来,这种方法帮助我减少了深层嵌套的 if else。除此之外,尝试将相关功能分成不同的方法。提供的示例方法在一种方法中塞满了太多逻辑。如果您有 ReSharper,它会建议您进行不错的改进,并且在一段时间后,它会成为一种习惯。
关于c# - 有没有更简单的方法将多个 if/else 语句相互写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863349/