c# union结构体_C# 中创建一个类似C 的union结构

本文探讨了C#中使用`StructLayout(LayoutKind.Explicit)`和`FieldOffset`属性创建类似C语言union的结构体。示例代码展示了如何在同一个内存位置存储不同类型的数据,包括字符串、字节和短整型,并演示了如何读取和操作这些数据。通过这个例子,读者可以更好地理解C#中结构体布局和内存对齐的概念。
摘要由CSDN通过智能技术生成

这个c# 代码片段使用ExplicitLayout attribute 来创建一个类似c 的union

using System.Runtime.InteropServices;

...

[StructLayout(LayoutKind.Explicit)]

internal struct Union

{

[FieldOffset (6)] internal byte byteData;

[FieldOffset (0)] internal string stringText;

[FieldOffset (4)] internal short unionShort;

[FieldOffset (4)] internal byte lowByte;

[FieldOffset (5)] internal byte highByte;

}

public class TestUnion

{

public static void Main( )

{

Union union = new Union ();

union.stringText = "Union";

union.byteData = 0xFF;

union.lowByte = 0x01;

union.highByte = 0x01;

Console.WriteLine (union.unionShort + " = " +

(union.highByte * 256 + union.lowByte).ToString());

}

}

标签:

代码

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值