C#中使用结构体实现Union数据类型

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大小。

猜你喜欢

转载自www.cnblogs.com/ming-4/p/12789903.html