Como: Criar uma união C/C++ usando atributos (C# e Visual Basic)

Usando atributos, você pode personalizar como estruturas são dispostas na memória. Por exemplo, você pode criar o que é conhecido como uma união em C/C++ usando o StructLayout(LayoutKind.Explicit) e FieldOffset atributos.

Exemplo

No segmento de código, todos os campos de TestUnion Iniciar no mesmo local na memória.

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

Veja a seguir outro exemplo onde iniciar de campos em diferentes explicitamente definir locais.

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

Os campos de número inteiro de dois i1 e i2, compartilhe os mesmos locais de memória, como lg. Esse tipo de controle sobre o layout de struct é útil ao usar invocação de plataforma.

Consulte também

Referência

Reflexão (C# e Visual Basic)

Atributos (C# e Visual Basic)

Criando os atributos personalizados (C# e Visual Basic)

Acessar atributos usando reflexão (C# e Visual Basic)

System.Reflection

Attribute

Conceitos

Guia de Programação C#

Estendendo metadados usando atributos

Outros recursos

Guia de programação Visual Basic