.net - 为什么可空类型会有这样的行为

标签 .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(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/

相关文章:

c# - 从 WPF 中的按钮继承的用户控件

vb.net - Visual Studio 2015 中的 WithEvents 错误?

VB.NET:向后台 worker 发送多个参数

database - 必须初始化不可为 null 的实例字段 'id',必须初始化不可为 null 的实例字段 '_database'。 flutter 中

c# - 返回可为空的字符串类型

c# - 将一系列项目添加到列表的开头?

c# - C#检测特定进程的CPU架构

c# - VB.net 的 InputDialog 的 C# 版本是什么?

unity3d - Unity 不序列化 int? field

c# - 如何确定我的 winform 在哪个监视器中?