c#:编写 v1 的更短方法! ? v2:!v2
我可以写
bool v1, v2;
// ...
编辑吗:我对造成的混乱感到非常抱歉。正确的说法应该是:
bool v3 = !v1 ? v2 : !v2;
ORIGINAL 我要求
bool v3 = v1 ? v2 : !v2;
更短?或者:是否有一个运算符会产生相同的结果?
所以我将 Anders Abels 的答案标记为正确,因为他回答了我最初的问题。我只需要颠倒他的答案即可。
Can I write
bool v1, v2;
// ...
EDIT: I am very sorry for the confusions. The correct statement should be:
bool v3 = !v1 ? v2 : !v2;
ORIGINAL I asked for
bool v3 = v1 ? v2 : !v2;
even shorter? Or: Is there an operator which will have the same result?
So I marked Anders Abels answer as correct, because he answered my initial question. I only need to invert his answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为
v1==v2
应该这样做。编辑:
对于更新的问题,它是
v1!=v2
或v1^v2
正如安德斯所说。I think
v1==v2
should do it.Edit:
For the updated question, it's
v1!=v2
, orv1^v2
as Anders said.弗拉德已经提供了正确答案。我只是添加一个简单的表格,可能有助于显示如何解决此类问题。
编辑:该表已更新以匹配更新的问题。
正如 Vlad 已经提到的,表达式可以重构为
!=
。添加括号是为了澄清。编译器不需要它们。Vlad already provided the correct answer. I'm just adding a simple table that might help showing how these kind of problems could be solved.
Edit: The table has been updated to match the updated question.
As Vlad has already metioned the expression can be refactored into
!=
. Parantheses added for clarification. They are not needed by the compiler.您可以使用
xor
(^
运算符),如果一个且只有一个操作数为true
,它将给出true
>。它会返回与你想要的相反的结果,所以你必须否定一切:You can use
xor
(the^
operator) which will givetrue
if one and only one of the operands istrue
. It will return the opposite of what you want, so you have to negate everything: