IronRuby System.DateTime NilClass
为什么与 null 比较如此不稳定?
只是代码。
IronRuby 0.9.4.0 on .NET 2.0.50727.4927
Copyright (c) Microsoft Corporation. All rights reserved.
>>> require 'System'
=> true
>>> i = System::Int32.MinValue
=> -2147483648
>>> i==nil
=> false
>>> d = System::DateTime.Now
=> 11.02.2010 14:15:02
>>> d==nil
(ir):1: can't convert NilClass into System::DateTime (TypeError)
>>>
在 9.1 中,此代码按预期工作。
编辑:
解决方法:
>>> i.nil?
=> false
>>> d.nil?
=> false
>>> nil
=> nil
>>> nil.nil?
=> true
>>>
Why comparing to null is so unstable?
Just code.
IronRuby 0.9.4.0 on .NET 2.0.50727.4927
Copyright (c) Microsoft Corporation. All rights reserved.
>>> require 'System'
=> true
>>> i = System::Int32.MinValue
=> -2147483648
>>> i==nil
=> false
>>> d = System::DateTime.Now
=> 11.02.2010 14:15:02
>>> d==nil
(ir):1: can't convert NilClass into System::DateTime (TypeError)
>>>
In 9.1 this code works as expected.
EDIT:
workaround:
>>> i.nil?
=> false
>>> d.nil?
=> false
>>> nil
=> nil
>>> nil.nil?
=> true
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,不一致是因为
System.DateTime
定义了它自己的 == 方法,而System.Int32
没有。此外,
System.Int32
是一个“特殊”类,IronRuby 将其直接映射到Fixnum
,因此当您调用System.Int32 == x
时>,您实际上是在调用内置的Fixnum#==
方法。考虑到这一点,会发生以下情况:
使用
Int32
时,映射到Fixnum
使用
Int16
时,它不映射到任何内容,并且不映射重载==
与
DateTime
不映射,但确实重载==
系统: :DateTime
重载==
方法仅接受其他System::DateTime
结构。然后,IronRuby 尝试将
nil
转换为这些结构之一,以便它可以调用该方法,然后该方法会失败并出现您看到的错误。这看起来不一致吗?是的。
难道真的不一致吗?我认为不。好吧,这并不比定义自己的
==
方法的任何其他 CLR 类型更加不一致。对我来说,仅使用System::DateTime
的特殊情况是没有意义的,但总的来说,这并不重要。在 ruby 中检查 null 的“正确”方法是调用
.nil?
,这适用于DateTime
或任何其他类/结构As far as I can tell, the inconsistency is because
System.DateTime
defines it's own == method, andSystem.Int32
does not.Furthermore,
System.Int32
is a "special" class in that IronRuby maps it directly toFixnum
, so when you callSystem.Int32 == x
, you're actually calling the built inFixnum#==
method.With that in mind, here's what happens:
With
Int32
, which maps toFixnum
With
Int16
which doesn't map to anything, and does not overload==
With
DateTime
which doesn't map, but does overload==
The
System::DateTime
overloaded==
method only accepts otherSystem::DateTime
structures.IronRuby then tries to convert
nil
to one of these structures so it can call the method, which then fails with the error you see.Does this appear inconsistent? Yes.
Is it actually inconsistent? I'd argue no. Well, no more inconsistent than any other CLR type that defines it's own
==
method. To me it makes no sense to just have a special case forSystem::DateTime
In general though, it doesn't matter. The "correct" way to check for null in ruby is to call
.nil?
, and this works well withDateTime
or any other class/struct