[译]Visual Basic 2005在语言上的增强(十一)无符号类型

类别:.NET开发 点击:0 评论:0 推荐:

Visual Basic 2005完全地支持了无符号类型。这些无符号类型名包括:
• SByte
• UShort
• UInteger
• ULong

除了只能存储非负整数以外,无符号类型和常规类型的工作原理是一样的。

当Visual Basic调用Win32的API、需要传入无符号类型的参数时,无符号类型就极为有用了。下面这段代码演示了如何调用Windows的MessageBox API:
Public Enum WindowsMessageResult As UInteger
    OK = 1
    Cancel = 8
End Enum

Private Const MB_OK As UInteger = 0
Private Const MB_ICONEXCLAMATION As UInteger = &H30
Private Const MB_OPTIONS As UInteger = MB_OK Or MB_ICONEXCLAMATION

Private Declare Auto Function Win_MB Lib _
    "user32.dll" Alias "MessageBox" _
    (ByVal hWnd As Integer, ByVal lpText As String, _
     ByVal lpCaption As String, ByVal uType As UInteger) _
     As UInteger

Public Function MessageThroughWindows(ByVal message As String, _
    ByVal caption As String) As WindowsMessageResult
    Dim r As UInteger = Win_MB(0, message, caption, MB_OPTIONS)
    Return CType(r, WindowsMessageResult)
End Function

你看,在Win_MB函数声明中的最后一个参数以及返回值都是UInteger类型的。

如果你想存储超过了Integer范围的数值,那么无符号类型也可以替你节省空间。Integer类型占用四字节的内存并且只能存储不超过2,147,483,648的正数或负数。UInteger类型也只占用四字节内存,却可以存储从零到4,294,967,295的数值。如果没有了无符号类型,你又不得不使用占用了八字节内存的Long来存储这么大的数值了。


@原文在此供网友们参考@

Unsigned Types

Visual Basic 2005 has full support for unsigned types. The unsigned type names are:
• SByte
• UShort
• UInteger
• ULong

The unsigned types work as regular types except the unsigned type can store only positive integers.

Unsigned types are most useful in Visual Basic for making Win32 API calls that take unsigned types as parameters. The following code illustrates a Windows MessageBox API call:
Public Enum WindowsMessageResult As UInteger
    OK = 1
    Cancel = 8
End Enum

Private Const MB_OK As UInteger = 0
Private Const MB_ICONEXCLAMATION As UInteger = &H30
Private Const MB_OPTIONS As UInteger = MB_OK Or MB_ICONEXCLAMATION

Private Declare Auto Function Win_MB Lib _
    "user32.dll" Alias "MessageBox" _
    (ByVal hWnd As Integer, ByVal lpText As String, _
     ByVal lpCaption As String, ByVal uType As UInteger) _
     As UInteger

Public Function MessageThroughWindows(ByVal message As String, _
    ByVal caption As String) As WindowsMessageResult
    Dim r As UInteger = Win_MB(0, message, caption, MB_OPTIONS)
    Return CType(r, WindowsMessageResult)
End Function

Notice the last parameter and return type on the Win_MB declaration are both UInteger types.

Unsigned types can also help you conserve memory if you need to store values larger than an Integer. The Integer type uses four bytes of memory and can store positive and negative values up to 2,147,483,648. The UInteger type also uses four bytes and can store a value between zero and 4,294,967,295. Without an unsigned type, you'd need to use a Long taking eight bytes of memory to store values this large.

本文地址:http://com.8s8s.com/it/it42062.htm