假设我有一个长而复杂的条件列表,这些条件必须为真才能运行 if 语句。
if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
DoSomethingInteresting();
}
通常,如果我被迫做这样的事情,我会把每条语句放在自己的行上,如下所示:
if
(
this == that
&& foo != bar
&& foo != that
&& pins != needles
&& apples != oranges
)
{
DoSomethingInteresting();
}
但我还是觉得这有点乱。我很想像这样将 if 语句的内容重构到它自己的属性中
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
但是这只是将所有困惑转移到 canDoSomethingInteresting()
中,并没有真正解决问题。
正如我所说,我的 goto 解决方案是中间的,因为它不会像最后一个那样混淆逻辑并且比第一个更具可读性。但必须有更好的方法!
响应 Sylon 评论的示例
bool canDoSomethingInteresting
{
get{
//If these were real values, we could be more descriptive ;)
bool thisIsThat = this == that;
bool fooIsntBar = foo != bar;
bool fooIsntThat = foo != that;
return
(
thisIsThat
&& fooIsntBar
&& fooIsntThat
);
}
}
if(canDoSomethingInteresting)
{
DoSomethingInteresting();
}
最佳答案
在我看来,将困惑转移到属性或方法中并不是一个坏主意。这样它是独立的,并且您执行 if(..) 检查的主要逻辑变得更具可读性。特别是如果要检查的条件列表很大,最好是在一个属性中,这样如果你需要重新使用你就不会重复该检查。
if(IsAllowed)
{
DoSomethingInteresting();
}
关于c# - 是否有一种更易读的方式来制作一长串 && 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208721/