作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个长而复杂的条件列表,这些条件必须为真才能运行 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/
我是一名优秀的程序员,十分优秀!