Share via


如何:使用特性创建 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 相同的内存位置。 使用平台调用时,这种结构布局控制很有用。

请参见

参考

反射(C# 和 Visual Basic)

特性(C# 和 Visual Basic)

创建自定义特性(C# 和 Visual Basic)

使用反射访问特性(C# 和 Visual Basic)

System.Reflection

Attribute

概念

C# 编程指南

利用特性扩展元数据

其他资源

Visual Basic 编程指南