藉由使用屬性,您可以自定義結構在記憶體中配置的方式。 例如,您可以使用 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
這兩個整數欄位 i1 和 i2 與 lg 共用相同的記憶體位置。 使用平台調用時,這種結構配置的控制很有用。