HOW TO:使用屬性建立 C/C++ 等位 (C# 和 Visual Basic)
經由使用屬性,您可以自訂結構在記憶體中的安排方式。 例如,您可以使用 StructLayout(LayoutKind.Explicit) 和 FieldOffset 屬性建立 C/C++ 中的等位。
範例
在這個程式碼區段中,TestUnion 的所有欄位都在記憶體中的同一個位置開始。
<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
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
[System.Runtime.InteropServices.FieldOffset(0)]
public int i;
[System.Runtime.InteropServices.FieldOffset(0)]
public double d;
[System.Runtime.InteropServices.FieldOffset(0)]
public char c;
[System.Runtime.InteropServices.FieldOffset(0)]
public byte b;
}
以下是另一個範例,其中欄位是在不同的明確設定位置開始。
<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
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
[System.Runtime.InteropServices.FieldOffset(0)]
public long lg;
[System.Runtime.InteropServices.FieldOffset(0)]
public int i1;
[System.Runtime.InteropServices.FieldOffset(4)]
public int i2;
[System.Runtime.InteropServices.FieldOffset(8)]
public double d;
[System.Runtime.InteropServices.FieldOffset(12)]
public char c;
[System.Runtime.InteropServices.FieldOffset(14)]
public byte b;
}
i1 和 i2 兩個整數欄位會共用與 lg 相同的記憶體位置。 當使用平台引動過程時,此種結構配置的控制項非常有用。