[英]Turn this if-then logic into a boolean expression?
I'm having a bit of a brain fart on making this code more concise(preferably a single boolean expression)我在使这段代码更简洁方面有点放屁(最好是单个 boolean 表达式)
This is my code:这是我的代码:
if (d.Unemployed)
{
if (type.Unemployed)
{
tmp.Unemployed = true;
}
else
{
tmp.Unemployed = false;
}
}
else
{
if (type.Unemployed)
{
tmp.Unemployed = false;
}
else
{
tmp.Unemployed = true;
}
}
Basically the point is that if either type
or d
is not unemployed, then tmp
should be set to not unemployed.基本上要点是,如果
type
或d
没有失业,则tmp
应设置为未失业。
How about:怎么样:
tmp.Unemployed = type.Unemployed == d.Unemployed;
If we construct a truth table by following the code, we get如果我们按照代码构造一个真值表,我们得到
d | type | tmp
---+------+----
1 | 1 | 1
---+------+----
1 | 0 | 0
----+-----+----
0 | 1 | 0
----+-----+----
0 | 0 | 1
The above is equivalent with the negation of the xor
operation.以上等价于
xor
或运算的否定。
tmp = not (d xor type)
If the language doesn't have the xor
operator we can use the !=
on boolean values.如果语言没有
xor
运算符,我们可以在 boolean 值上使用!=
。
tmp = ! (d != type);
// or
tmp = d == type;
Thinking about how much "brain fart" this caused you I would consider using a well named variable to avoid having to go through this mental process again in future.考虑到这给你造成了多少“大脑放屁”,我会考虑使用一个命名良好的变量,以避免将来再次通过这个心理过程进行 go。 Something like this:
像这样的东西:
isTmpUnemployed = (type.Unemployed == d.Unemployed);
tmp.Unemployed = isTmpUnemployed;
tmp.Unemployed = d.Unemployed || type.Unemployed ? !tmp.Unemployed : null;
The above code means "both unemployed or both not unemployed".上述代码的意思是“都失业或都没有失业”。 Thus, not (A xor B):
因此,不是(A xor B):
tmp.Unemployed = ! ( D.Unemployed ^ type.Unemployed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.