我知道 undefined 不等于 null。但是在 c#、C++ 或 java 等其他语言中是否有类似的概念?
3 回答
除了@DaoWen 的例子...
Perl 有一个与 null 或 0 分开的未定义值(通常缩写为“undef”)。它可以用defined进行测试,通常表明发生了运行时错误(当不使用异常时)。在布尔上下文中,它被认为是错误的。你可以通过...
- 声明但从不初始化变量:
my $foo;
- 从子例程中不返回任何内容:
sub foo { return; }
- 将变量显式设置为 undef:
$foo = undef;
SQL 具有 NULL 值。与未定义的值不同,它不是假的。这是第三个布尔状态,既不是真也不是假。这种三元逻辑经常使可能将 NULL 与 false 混淆的人绊倒。
javascript 有未使用的变量和属性默认为未定义,以帮助防止编写糟糕的网页完全失败。大多数其他语言具有必须有意使用的类似功能。静态类型语言有一个额外的限制,即必须声明属性或变量的类型,这通常意味着变量可以为 NULL,但不会完全未定义(它具有类型)。另一方面,大多数面向对象的语言都能够查找属性并返回它,或者如果该属性在对象上不存在,则返回指定的替代项。考虑:
class Undefined(object):
pass
a=object()
b=getattr(a,'b',Undefined)
print b is Undefined
将打印True
。
Java has a similar ability but of course you have to know what the type of the attribute is if it exists, you'll see it used with reflection. I assume there is something similar for c++, but I don't know any details.
As a side note, you can implement Undefined at the class and module level in Python with some mild black magic. In the class's __getattribute__
method, have it return Undefined
if the attribute isn't in the class's attributes, and then create a subclass of types.ModuleType
and define a __getattribute__
on it that also returns Undefined
, but I suggest thinking hard about that before doing it, as I can't see a case where you'd actually want any name to reference a value even if it's a typo...