【发布时间】:2013-08-29 14:42:35
【问题描述】:
是否可以检查语句块的每一行的条件是否为真,而无需在每行之前添加if (condition)?
例如:
if (condition)
{
DoSomething();
DoSomethingElse();
DoAnotherThing();
}
在某个时刻,另一个后台进程可能在执行DoSomethingElse() 之前将condition 设置为false。本质上,我正在寻找一种有效且更简单的说法:
if (condition) DoSomething();
if (condition) DoSomethingElse();
if (condition) DoAnotherThing();
实际上,这是一段很长的代码,执行一次,如果在任何时候更改了特定标志,我想放弃它。
收紧此类代码的最佳方法是什么。
【问题讨论】:
-
多态性。创建表示实体 DoSomething()、DoSomethingElse() 和 DoAnotherThing() 的类。然后调用 myclass1.doThing(); myclass2.doThing() 和 myclass3.doThing()。在这些方法中,重定向到单个方法,该方法检查条件,然后运行适当的函数。 sourcemaking.com/refactoring/…
-
如果,否则如果,如果,否则...?
标签: c# if-statement redundancy