C#中使用結構體實現Union數據類型:
C#中不自帶Union數據類型,可以使用以下方式實現:
引用:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text;
定義: [StructLayout(LayoutKind.Explicit, Size = 4)] public struct Union { [FieldOffset(0)] public Byte b0; [FieldOffset(1)] public Byte b1; [FieldOffset(2)] public Byte b2; [FieldOffset(3)] public Byte b3; [FieldOffset(0)] public Int32 i; [FieldOffset(0)] public Single f; }
使用: Union u = new Union(); u.i = 1024; Console.WriteLine(u.b1 == 4);
聯合體所有數據共用一段內存,可以使用int類型i賦值,之后使用byte類型b0讀取int類型的第一個byte大小。