VB.NET中的可空类型是什么?

33

可空类型在VB.NET中是否可用?如果可用,是否可以使用可空整数与接受NULL值的SQL Server字段一起使用?请提供示例。

6个回答

58

VB.Net确实有可空类型,可以通过以下两种不同的方式进行声明。

Dim iNullable As Integer?
或者
Dim iNullable As Nullable(Of Integer)

7
实际上有3种方法:Dim iNullable? as Integer。 - Ed_
3
4种方法:dim x%? - Chalky

44

7
实际上,在VB.NET中,您可以将Nothing赋值给整数: Dim a As Integer = Nothing但是在此之后,以下条件成立: a = 0 - Jochen
为了澄清,VB.NET 中的 Nothing 就像 C# 中的 default(T)。当与值类型或引用类型一起使用时,它的行为是不同的。 - nikeee

7
在 .NET 中,整数(例如 System.Int32)不能直接为空;然而,有一个名为 Nullable-of-T 的类型可使任何值类型变得类似于可空。请注意,您可能需要检查数据库中的 DBNull 而不是 null/Nothing

因此,您可以做出非常相似的事情。


4
在许多情况下,Nothing会被转换为默认值。如果要像使用null一样使用Nothing,则需要将其强制转换为正确的可空类型。
Dim str As String
Dim int As Nullable(Of Integer) ' or use As Integer?
Dim reader As SqlDataReader
Dim colA As Integer = reader.GetOrdinal("colA")
Dim colB As Integer = reader.GetOrdinal("colB")
str = If(reader.IsDBNull(colA), DirectCast(Nothing, String), reader.GetString(colA))
int = If(reader.IsDBNull(colB), DirectCast(Nothing, Nullable(Of Integer)), reader.GetInt32(colB))

2

如下所述,我知道从客户端代码将NULL输入数据库的唯一方法是在SQL中使用等于NULL的默认值。

因此,在更新/插入存储过程中,您可以使用以下内容:

create proc dbo.UpdateSomeTable
    @Id int, 
    @Status bit = NULL
as
begin
    update dbo.SomeTable
    set Status = @Status
    where Id = @Id
end

在代码中的某个地方

Dim pars As List(Of SqlParameter) = New List(Of SqlParameter)
With pars
    .Add(New SqlParameter("@Id", LogbookNoteId))
    If Flag Then
        .Add(New SqlParameter("@Status", Flag))
    End If
End With
ExecuteNonQuery("dbo.UpdateSomeTable", pars, CommandType.StoredProcedure)

1

不行。您必须修改插入或更新查询,以便不添加(或更新)该值以在数据库中获取空值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接