此文章由人工翻译。 将光标移到文章的句子上，以查看原文。 更多信息。 译文 原文

# 可以为 Null 的值类型 (Visual Basic)

Visual Studio 2013

```Dim ridesBusToWork1? As Boolean
Dim ridesBusToWork2 As Boolean?
Dim ridesBusToWork3 As Nullable(Of Boolean)
```

## 使用可以为 null 的类型的变量

### 默认值

```Dim numberOfChildren? As Integer
```

null 值对于指示未定义的或未知的值很有用。 如果 numberOfChildren 已被声明为 Integer，则不会有值可以指出当前没有可用的信息。

### 存储值

```numberOfChildren = 2
```

```numberOfChildren = Nothing
```

### 检索值

```If numberOfChildren.HasValue Then
MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
MsgBox("It is not known how many children there are.")
End If
```

## 比较可以为 Null 的类型

b1

b2

b1 And b2

b1 Or b2

Nothing

Nothing

Nothing

Nothing

Nothing

True

Nothing

True

Nothing

False

False

Nothing

True

Nothing

Nothing

True

True

True

True

True

True

False

False

True

False

Nothing

False

Nothing

False

True

False

True

False

False

False

False

```Dim b1? As Boolean
Dim b2? As Boolean
b1 = True
b2 = Nothing

' The following If statement displays "Expression is not true".
If (b1 And b2) Then
Console.WriteLine("Expression is true")
Else
Console.WriteLine("Expression is not true")
End If

' The following If statement displays "Expression is not false".
If Not (b1 And b2) Then
Console.WriteLine("Expression is false")
Else
Console.WriteLine("Expression is not false")
End If
```

Expression is not true

Expression is not false

AndAlso OrElse 使用的是短路计算，当第一个操作数计算结果为 Nothing 时，它们必须计算第二个操作数。

## 传播

```' Variable n is a nullable type, but both m and n have proper values.
Dim m As Integer = 3
Dim n? As Integer = 2

' The comparison evaluated is 3>2, but compare1 is inferred to be of
' type Boolean?.
Dim compare1 = m > n
' The values summed are 3 and 2, but sum1 is inferred to be of type Integer?.
Dim sum1 = m + n

' The following line displays: 3 * 2 * 5 * True
Console.WriteLine(m & " * " & n & " * " & sum1 & " * " & compare1)
```

```' Change the value of n to Nothing.
n = Nothing

Dim compare2 = m > n
Dim sum2 = m + n

' Because the values of n, compare2, and sum2 are all Nothing, the
' following line displays 3 * * *
Console.WriteLine(m & " * " & n & " * " & sum2 & " * " & compare2)
```