为什么下面的代码不会导致编译错误,即使我有Option Strict On
?为什么在选项严格的情况下允许从Double到Single分配
Dim value As Single = 12345.12345 ' No error
默认情况下,数字文字由编译器解释为Double
。从Double
转换为Single
是一个缩小的转换(分配,在这种情况下,实际上是将值四舍五入到12345.123
)。按照MSDN article,Option Strict On
具有以下作用:
Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.
基于这样的描述,我的示例代码应导致错误。事实上,即使我的文字后明确指定类型的字符,它仍然不认为这是一个错误:
Dim value As Single = 12345.12345R 'Still no error, despite the "R"
即使这不会导致错误:
Dim value As Single = CDbl(12345.12345) 'Still no error, despite the CDbl() conversion
但,这确实会导致一个错误,因为我期望:
Dim value1 As Double = 12345.12345
Dim value2 As Single = value1 ' Causes "Option Strict On disallows implicit conversions from 'Double' to 'Single'" error
同样,这也失败了,正如预期:
Public Function GetValue() As Double
Return 12345.12345
End Function
' ...
Dim value As Single = GetValue() ' Causes "Option Strict On disallows implicit conversions from 'Double' to 'Single'" error
作为一个侧面说明,下面的失败在C#中,符合市场预期:
float x = 12345.12345; ' Causes error in C#
因此,它并不适用于所有.NET语言的问题。它似乎是VB.NET的一个特点。
此外,VB.NET不允许这样的隐式转换,即使它是从文字转换:
Dim x As Integer = 1.5 ' Causes error
所以,我的问题是,为什么VB.NET这种工作方式?这对我来说似乎是一个缺陷,但也许有一个很好的解释,为什么它允许将文字的转换范围缩小到Single
,但在其他任何情况下都不会。
“*数字文字默认情况下由编译器解释为Double。*”您确定这是真的?你有参考吗?因为我认为它被解释为一个Single,就像历史上那样,VB/Basic的先前化身已经完成了它。 (这就是为什么我用附加的“#”编写这样的东西的原因。) – RBarryYoung 2015-02-09 17:11:55
OK,根据这个:https://msdn.microsoft.com/en-us/library/dzy06xhf.aspx你是正确的... – RBarryYoung 2015-02-09 17:14:10
非常奇怪!这也适用于没有投诉:Dim value As Single = Double.MaxValue以及Double.PositiveInfinity等 – theduck 2015-02-09 17:55:29