如何在 C# 使用屬性建立 C/C++ 集合聯集

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

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

[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(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;
}

i1i2 組合這兩個整數欄位和 lg 共用相同的記憶體位置。 lg 會使用前 8 個位元組,或者 i1 會使用前 4 個位元組,而 i2 會使用後面 4 個位元組。 使用平台叫用時,這種結構配置控制項很有用。

另請參閱