C# bool 表达式求值顺序

发布于 2024-08-11 07:33:15 字数 846 浏览 1 评论 0 原文

可能的重复:
== 运算符和操作数

可能的重复:
if(a==5) 之间有什么区别或者 C# 中的 if(5==a) ?
== 运算符和操作数

好吧,这可能是个愚蠢的问题,但是在谷歌中搜索(似乎不能实际上搜索精确的短语,即使带引号)

之间存在任何差异怎么办?

如果 if(false == ){

if( == false){ 在

C# 中?我熟悉 C# 的表达式求值,并且了解如果您执行以下操作,顺序将如何有意义:

if(AccountIsInvalid || AccountIsUnregistered)

我不需要大量课程,但想了解原因有些人更喜欢使用 false==.... 路线做事。

Possible Duplicate:
== Operator and operands

Possible Duplicates:
Is there any difference between if(a==5) or if(5==a) in C#?
== Operator and operands

Ok, this may be stupid question, but searching in google (cant seem to ACTUALLY search for an exact phrase even with quotes)

What if any difference is there between

if(false == <somecondition>){

and

if(<somecondition> == false){

in C#? I am familiar with c#'s expression evalution, and understand how the order would make sense if you were doing something like:

if(AccountIsInvalid || AccountIsUnregistered)

I dont need a huge lesson, but would like to understand why some people prefer to do things with false==.... route.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

生死何惧 2024-08-18 07:33:15

就我个人而言,我从不将任何东西与虚假或真实进行比较。

我会选择:

if (!somecondition) 

或:

if (somecondition)

Personally, I never compare anything to false or true.

I would go with:

if (!somecondition) 

or:

if (somecondition)
埋情葬爱 2024-08-18 07:33:15

在 C 中,也许有一些理由这样做,因为你很容易犯错误并使用赋值运算符而不是比较运算符,但在 C# 中它不应该有任何区别 - 你将得到一个编译如果您使用赋值运算符,则会发出警告。如果赋值是不同的类型(例如 int),则会导致错误,因为结果不是 if 语句的合法表达式。

我更希望它是

if (!<somecondition>)
{
  ...
}

真实的,而不是与错误(或真实的)进行比较。

In C there would have been, perhaps, some reason to do this as you could easily make a mistake and use the assignment operator instead of the comparison operator, but in C# it shouldn't make any difference -- you'll get a compile warning if you use the assignment operator. If the assignment were a different type (say int), it would result in an error, since the result wouldn't be a legal expression for the if statement.

I would prefer it to be

if (!<somecondition>)
{
  ...
}

rather than a comparison to false (or true, for that matter).

◇流星雨 2024-08-18 07:33:15

在执行任何优化或短路之前,编译器需要将 解析为 truefalse 值,因此没有理由为什么编译器会计算表达式 ; == falsefalse == 任何不同。

这肯定是一个风格问题,而且只是风格问题。

Before performing any optimizations or short-circuits, the compiler needs to resolve <somecondition> to true or false value, thus there is no reason why the compiler would evaluate the expressions <somecondition> == false and false == <somecondition> any differently.

This must surely be an issue of style, and style only.

彼岸花ソ最美的依靠 2024-08-18 07:33:15

这在 C# 中并不重要,就像在 c/c++ 中一样,因为条件必须计算为布尔值。

This doesn't matter in C# like it does in c/c++ because conditions must evaluate to a boolean.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文