||(或)Java 与 .Net 中的逻辑运算符
我已经用 Java(主要)和 .Net 进行编码有一段时间了。
我发现.Net 中的 ||
逻辑运算符与 Java 中的 ||
运算符的结果不同。
让我们看一下下面的 Java 代码:
Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println("Object is null");
}
上面代码的结果将是:
Object is null
原因是因为 obj == null
是 true< /code> 并且第二个表达式未被评估。如果是这样,我就会收到
java.lang.NullPointerException
。
如果我使用单个或 (|
),我也会收到一个 NullPointerException
(两者都会被评估)。
我的问题如下:
如果代码是 C#,我将始终收到 ObjectReferenceNotSet 等异常,因为 obj 值为 null 并且始终计算第二个表达式(无论运算符如何),这意味着结果C# 中与 Java 中不同。 如果我想更改 C# 代码以使其正常工作,我必须创建两个 if 语句。
是否有更简单的方法可以在 C# 中执行此操作,类似于 Java ? (将其保留在一个 if 和 2 个表达式中)
谢谢。
I have been coding in Java(Mainly) and .Net for a while.
What I found is that the ||
logical operator in .Net is different in result to the ||
operator in Java.
Lets look at the following Java code:
Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println("Object is null");
}
The result of the code above will be:
Object is null
The reason for that is because obj == null
is true
and the second expression wasn't evaluated. If it was, I would have received a java.lang.NullPointerException
.
And if I used the single or (|
) I would also received a NullPointerException
(Both are evaluated).
My question is the following:
If the code was C#, I will always get a ObjectReferenceNotSet etc. exception because the obj value is null and the second expression is always evaluated (Regardless of the operator), meaning the result is different in C# than in Java.
If I would to change the C# code to work properly, I have to create two if statements.
Is there not an easier way to do this in C# to be similar to Java? (Keep it in one if with 2 expressions)
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C# 中的
||
运算符是短路运算符,就像 Java 中一样。正如&&
一样。|
和&
运算符不是短路的,就像在 Java 中一样。如果结果不同,则代码中存在错误。您能给我们展示一下有问题的 C# 吗?
这工作正常:
The
||
operator in C# is short-circuiting, just like in Java. As is&&
. The|
and&
operators are not short-circuiting, just like in Java.If your results are different, there is a bug in the code. Can you show us the offending C# please?
This works fine:
||运算符在 Java 和 C# 中的含义完全相同。它称为条件逻辑 OR,或“短路”逻辑 OR 运算符:
http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx
The || operator has exactly the same meaning in Java and C#. It is called a conditional logical OR, or "short-circuiting" logical OR operator:
http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx
此行为是严格的 Java 语言功能:
定义类似的规则 java 条件-和运算符。
与 C# 比较(相同):
This behaviour is a strict java language feature:
Similar rules are defined for the java conditional-and operator.
Compare (identical) to C#:
这称为“短路评估”。无需评估下一条语句。这是 Java 中的一个很好的功能。
It's called "short circuit evaluation". There is no need to evaluate the next statement. This is a nice feature in Java.