如何:使用屬性建立 C/C++ 等位 (Visual Basic)

您可以使用屬性,自訂如何在記憶體中配置結構。 例如,您可以使用 StructLayout(LayoutKind.Explicit)FieldOffset 屬性,以 C/C++ 建立所謂的等位。

範例 1

在此程式碼片段中,TestUnion 的所有欄位都在記憶體的同一位置開始。

' Add an Imports statement for System.Runtime.InteropServices.

<System.Runtime.InteropServices.StructLayout(
      System.Runtime.InteropServices.LayoutKind.Explicit)>
Structure TestUnion
    <System.Runtime.InteropServices.FieldOffset(0)>
    Public i As Integer

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public d As Double

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public c As Char

    <System.Runtime.InteropServices.FieldOffset(0)>
    Public b As Byte
End Structure

範例 2

以下是另一個範例,欄位從明確設定的不同位置開始。

' Add an Imports statement for System.Runtime.InteropServices.

 <System.Runtime.InteropServices.StructLayout(
      System.Runtime.InteropServices.LayoutKind.Explicit)>
Structure TestExplicit
     <System.Runtime.InteropServices.FieldOffset(0)>
     Public lg As Long

     <System.Runtime.InteropServices.FieldOffset(0)>
     Public i1 As Integer

     <System.Runtime.InteropServices.FieldOffset(4)>
     Public i2 As Integer

     <System.Runtime.InteropServices.FieldOffset(8)>
     Public d As Double

     <System.Runtime.InteropServices.FieldOffset(12)>
     Public c As Char

     <System.Runtime.InteropServices.FieldOffset(14)>
     Public b As Byte
 End Structure

i1i2 這兩個整數欄位和 lg 共用相同的記憶體位置。 使用平台叫用時,這種結構配置控制項很有用。

另請參閱