Share via


HOW TO:以不帶正負號型別最佳化正整數的儲存 (Visual Basic)

如果您的變數僅包含正值 (或 0),且這些值絕不會超過 4,294,967,295,則可以將變數宣告為 UInteger,而非 Long。

使用 UInteger 的優點在於,32 位元的整數型別 Integer 和 UInteger 是 32 位元平台上最有效的資料型別,並可提供應用程式最佳化的效能。

當正值絕不會超過 2,147,483,647 時,就可以使用 Integer 變數。

若要宣告僅含正值的整數

  • 將變數宣告為 As UInteger。 下列範例將說明這點。

    Public Function memoryRequired(ByVal m As UInteger) As UInteger
        Static r As UInteger = 0
        Try
            r += m
        Catch eo As System.OverflowException
            r = 0
        Catch ex As System.Exception
            MsgBox("Incrementing required memory causes """ & ex.Message & """")
        End Try
        Return r
    End Function
    

    您可以使用下列程式碼測試函式 memoryRequired:

    Public Sub consumeMemoryRequired()
        Dim m1 As UInteger = UInteger.MaxValue - 100
        Dim m2 As UInteger = 100
        MsgBox("Max = " & CStr(UInteger.MaxValue) & vbCrLf & 
            CStr(m1) & " -> " & CStr(memoryRequired(m1)) & vbCrLf & 
            "+ " & CStr(m2) & " -> " & CStr(memoryRequired(m2)) 
            & vbCrLf & "+ 1 -> " & CStr(memoryRequired(1)))
    End Sub
    

    警告

    UInteger 資料型別不屬於 Common Language Specification (CLS) 的一部分,所以符合 CLS 標準的程式碼不可以採納使用此資料型別的元件。

請參閱

工作

HOW TO:呼叫使用不帶正負號型別的 Windows 函式 (Visual Basic)

參考

資料型別摘要 (Visual Basic)

Integer 資料型別 (Visual Basic)

UInteger 資料型別