问题描述
使用VB的 Option Strict On
,为什么 Nullable(Of T)
不需要显式转换为T的界面,当它需要一个 T
?
With VB's Option Strict On
, why does a Nullable(Of T)
not require an explicit cast to an interface of T when it does require one to T
?
即
Dim x As Integer? = 5
Dim y As Integer
Dim z As IComparable
y = x ' Fails to compile with error
' "Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'."
z = x ' Succeeds
编辑:由@SSS显示为(某种),部分答案是 Nullable
值是否可以为空,并且可以 Nothing
,这对参考来说没问题像一个界面。因此转换将始终成功,不像转换为 T
的情况(当 Nullable
没有值时失败)所以它可以看作是一种隐含的转换。
As (sort of) shown by @SSS, part of the answer is that Nullable
values are, well, nullable, and can be Nothing
, which is fine for a reference like an interface. So this conversion will always succeed, unlike the conversion to T
case (which fails when the Nullable
has no value), and so it can be seen as an implicit conversion.
我的问题现在变成了怎么样?。如何从 Nullable(Of T)
(它没有自己的接口)到 T
理论上协商了吗?
My question now becomes "how?". How is the conversion from a Nullable(Of T)
(which has no interfaces of its own) to an interface of T
theoretically negotiated?
我知道实现是框Nullable< T>
,它有效地剥离了 Nullable
包装器,但我在这里确认了这个概念......
I know the implementation is box Nullable<T>
, which effectively strips the Nullable
wrapper, but I'm confirming the concept here...
(所以我会查看文档并查看是否他们解释了这一点。)
(So I'll review the documentation and see if they explain this.)
推荐答案
如果没有实际阅读文档,我将尝试回答:
Without actually reading documentation yet, I'm going to attempt an answer:
首先,更高级别的答案是向界面投射 Nullable
是安全的并且不会抛出,所以它是逻辑上是加宽
运算符,不应该是显式的(与 T
的转换相比,当 .HasValue 是 False
它会抛出,所以它不应该隐含 Option Strict On
)。
Firstly, the higher-level answer is that casting a Nullable
to an interface is "safe" and will not throw, so it is logically a Widening
operator and should not need to be explicit (compared to casting to T
, when .HasValue
is False
it throws, so it should not be implicit with Option Strict On
).
然而,从技术上讲,如何是bi t obscure:尽管 Nullable
的某些行为是通过反射提供的元数据中编码的,但它的大部分魔力都隐藏在:
However, technically the "how" is a bit obscure: Even though some of the behaviour of Nullable
is encoded in the metadata available via reflection, much of its "magic" is hidden in:
-
框
的运行时行为Nullable
(因此编译器知道何时离开提升,并且 - Eric Lippert在他的及其在VB.NET中的等价物。
- the runtime behaviour of
box
on aNullable
(and thus the compiler knows when to leave "lifting" to that), and - the other points made by Eric Lippert in his answer for C# and their equivalent in VB.NET.
它看起来像是宣布在VS2k5的后期测试版中对 Nullable
支持的更改也与此相关。
It looks like S. Somasegar's blog post announcing changes to Nullable
support in a late beta release for VS2k5 is also relevant here.
这篇关于Nullables的隐式界面演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!