我在可空类型方面遇到了麻烦,因此我编写了以下程序来演示我遇到的问题,但对结果感到困惑。程序如下:
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 有值?
最佳答案
GetNothingString 返回字符串类型的对象。关闭选项 strict 后,VB.Net 编译器允许这样做,但由于字符串不能直接分配给 Nullable(Of Integer),因此它会插入代码以将字符串转换为整数。您可以使用反射器验证这一点:例如当反编译为VB.Net时,代码如下所示:
Dim k As Nullable(Of Integer) = Conversions.ToInteger(Module1.GetNothingString)
由于此转换函数返回一个 int (Integer),而不是一个可以为 null 的 int,因此返回的默认值不能为 Nothing,而必须是一个有效的整数 0。
从对象转换为 Integer? 的代码,OTOH,是直接转换:
Dim j As Nullable(Of Integer) = DirectCast(Module1.GetNothing, Nullable(Of Integer))
如果您从该函数返回除 Nothing 以外的任何内容,DirectCast 将在运行时失败并出现 InvalidCastException。
关于.net - 为什么可空类型会有这样的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611783/