C# 条件 AND (&&) OR (||) 优先级 [英] C# conditional AND (&&) OR (||) precedence

查看:22
本文介绍了C# 条件 AND (&&) OR (||) 优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作中,我们总是会遇到不必要的编码争论.今天我问条件 AND (&&) 或 OR (||) 是否具有更高的优先级.我的一位同事坚持说他们有相同的优先级,我有疑问,所以我查了一下.

We get into unnecessary coding arguments at my work all-the-time. Today I asked if conditional AND (&&) or OR (||) had higher precedence. One of my coworkers insisted that they had the same precedence, I had doubts, so I looked it up.

根据 MSDN,AND (&&) 的优先级高于 OR (||).但是,您能向持怀疑态度的同事证明这一点吗?

According to MSDN AND (&&) has higher precedence than OR (||). But, can you prove it to a skeptical coworker?

http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx

bool result = false || true && false; // --> false
// is the same result as
bool result = (false || true) && false; // --> false
// even though I know that the first statement is evaluated as 
bool result = false || (true && false); // --> false

所以我的问题是你如何用代码证明 AND (&&) 比 OR (||) 具有更高的优先级?如果你的回答是没关系,那为什么要在语言中这样构建呢?

So my question is how do you prove with code that AND (&&) has a higher precedence that OR (||)? If your answer is it doesn't matter, then why is it built that way in the language?

推荐答案

将第一个false改为true.我知道拥有 (true || true) 似乎很愚蠢,但它证明了你的观点.

Change the first false by true. I know it seems stupid to have (true || true) but it proves your point.

bool result = true || true && false;   // --> true 
     result = (true || true) && false; // --> false
     result = true || (true && false); // --> true

这篇关于C# 条件 AND (&&) OR (||) 优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆