为什么Java和C#没有隐式转换为布尔? [英] Why do Java and C# not have implicit conversions to boolean?

查看:219
本文介绍了为什么Java和C#没有隐式转换为布尔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始的Java它已经非常加重对我来说,它不支持从数字类型布尔的隐式转换,所以你不能做这样的事情:

Since I started Java it's been very aggravating for me that it doesn't support implicit conversions from numeric types to booleans, so you can't do things like:

if (flags & 0x80) { ... }

相反,你必须去通过这个愚蠢:

instead you have to go through this lunacy:

if ((flags & 0x80) != 0) { ... }

这是一个与零和对象相同。所有其他类似C语言,我知道包括JavaScript允许的话,所以我认为Java的只是鲁钝,但我刚刚发现,C#是相同的(至少对于数字,不知道空/对象):
<一href=\"http://msdn.microsoft.com/en-us/library/c8f5xwh7(VS.71).aspx\">http://msdn.microsoft.com/en-us/library/c8f5xwh7(VS.71).aspx

微软改变了它的目的,从C ++,为什么?显然,我失去了一些东西。为什么要改变(我认为是)世界上最自然不过的事,使之不再打字?究竟什么是错呢?

Microsoft changed it on purpose from C++, so why? Clearly I'm missing something. Why change (what I thought was) the most natural thing in the world to make it longer to type? What on Earth is wrong with it?

推荐答案

有关清晰度。这让下面的错误只是非法的:

For clarity. It makes the following mistake simply illegal:

int x = ...;

if (x = 0)  // in C: assign 0 to x and always evaluate to false 
   ....     // never executed

请注意:最现代的C / C ++编译器会给出简单模式的警告(但不是一个错误),但也有可能的许多变化。它可以在你攀升。

Note: most modern C / C++ compilers will give a Warning (but not an Error) on this straightforward pattern, but there are many variations possible. It can creep up on you.

这篇关于为什么Java和C#没有隐式转换为布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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