.net 为什么可空类型会有这种行为
我遇到了可空类型的问题,所以我编写了以下程序来演示我遇到的问题,结果让我感到困惑。节目如下:.net 为什么可空类型会有这种行为,.net,vb.net,nullable,.net,Vb.net,Nullable,我遇到了可空类型的问题,所以我编写了以下程序来演示我遇到的问题,结果让我感到困惑。节目如下: Module Module1 Public Sub Main() Dim i As Integer? = Nothing Dim j As Integer? = GetNothing() Dim k As Integer? = GetNothingString() If i.HasValue Then System.Console.WriteLine(
Module Module1
Public Sub Main()
Dim i As Integer? = Nothing
Dim j As Integer? = GetNothing()
Dim k As Integer? = GetNothingString()
If i.HasValue Then
System.Console.WriteLine(String.Format("i has a value of {0}", i))
End If
If j.HasValue Then
System.Console.WriteLine(String.Format("j has a value of {0}", j))
End If
If k.HasValue Then
System.Console.WriteLine(String.Format("k has a value of {0}", k))
End If
System.Console.ReadKey()
End Sub
Public Function GetNothingString() As String
Return Nothing
End Function
Public Function GetNothing() As Object
Return Nothing
End Function
End Module
程序的输出为:
k的值为0
为什么只有k有一个值?它与字符串到整数的隐式转换有关 其他的则直接设置为Nothing,或者将Nothing作为发送给它的对象,没有隐式转换。然而,字符串却可以
请在“选项严格”处于启用状态时重试。我打赌没有打印。GetNothingString返回string类型的对象。关闭option strict后,VB.Net编译器允许这样做,但由于不能将字符串直接分配给可为空的(Of Integer),因此它会插入代码以将字符串转换为整数。您可以使用reflector验证这一点:例如,当反编译到VB.Net时,代码如下所示:
Dim k As Nullable(Of Integer) = Conversions.ToInteger(Module1.GetNothingString)
由于此转换函数返回int(整数),而不是可为null的int,因此返回的默认值不能为Nothing,但必须为有效整数0
从object到Integer?的转换代码OTOH是直接转换:
Dim j As Nullable(Of Integer) = DirectCast(Module1.GetNothing, Nullable(Of Integer))
如果从该函数返回除Nothing以外的任何内容,DirectCast将在运行时失败,并出现InvalidCastException