首页 > 解决方案 > 接受空值的VB.Net函数?

问题描述

我想制作一个操纵空值的子。这个想法是让它接受任何可以为空的变量,如果它有一个值,那么覆盖一个不同的值。这是我写的:

Dim a as int? = 0
Dim b as int? = 1

Sub ApplyChange(Byref Old As Nullable, ByRef Change as Nullable)
    If Change.HasValue Then
        Old = Change
    End IF
End Sub

ApplyChange(a, b)

问题是,我收到一个错误“HasValue 不是 Nullable 的成员”并且“int?不能转换为 Nullable”。这里发生了什么?我该如何制作一个只接受可为空的子?

标签: vb.netgenericsnullable

解决方案


不要使用Nullable类作为参数类型。使用Nullable(Of T)结构,这是您的变量被声明为的结构。这个:

Dim a As Integer? = 0
Dim b As Integer? = 1

是这个的简写:

Dim a As Nullable(Of Integer) = 0
Dim b As Nullable(Of Integer) = 1

这意味着您的方法可以是这样的:

Sub ApplyChange(Of T As Structure)(ByRef Old As Nullable(Of T), Change As Nullable(Of T))
    If Change.HasValue Then
        Old = Change
    End If
End Sub

同样,ByRef如果您没有设置参数或其任何成员,则不需要。

使用相同的速记:

Sub ApplyChange(Of T As Structure)(ByRef Old As T?, Change As T?)
    If Change.HasValue Then
        Old = Change
    End If
End Sub

推荐阅读