C#相当于C union

5 c c# unions

C#中C++联合重复

是否有C#等效于C union typedef?C#中的以下内容相当于什么?

typedef union byte_array
{
    struct{byte byte1; byte byte2; byte byte3; byte byte4;};
    struct{int int1; int int2;};
};byte_array
Run Code Online (Sandbox Code Playgroud)

CSh*_*per 5

C#本身不支持联合的C / C ++概念。但是,您可以使用StructLayout(LayoutKind.Explicit)和FieldOffset属性来创建等效功能。请注意,这仅适用于基本类型(例如int和float)。

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
    [FieldOffset(0)]
    public byte byte1;

    [FieldOffset(1)]
    public byte byte2;

    [FieldOffset(2)]
    public byte byte3;

    [FieldOffset(3)]
    public byte byte4;

    [FieldOffset(0)]
    public short int1;

    [FieldOffset(2)]
    public short int2;
}
Run Code Online (Sandbox Code Playgroud)