【发布时间】:2016-11-16 10:05:12
【问题描述】:
我在 C# 中声明了类似于 C++ 中的 union:
[StructLayout(LayoutKind.Explicit, Size = 5)]
public struct Marker
{
[FieldOffset(0)] public byte label;
[FieldOffset(1)] public int count;
[FieldOffset(1)] private byte count_0;
[FieldOffset(2)] private byte count_1;
[FieldOffset(3)] private byte count_2;
[FieldOffset(4)] private byte count_3;
}
我还有大小为 5 的 byte[] bytes。我需要将我的数组转换为 Marker 对象。我可以通过以下方式做到这一点:
var marker = new Marker
{
label = bytes[0],
count = BitConverter.ToInt32(bytes, 1)
}
或者:
var marker = new Marker
{
label = bytes[0],
count_0 = bytes[1],
count_1 = bytes[2],
count_2 = bytes[3],
count_3 = bytes[4]
}
没关系,但我认为从性能角度来看,可以通过更优化的方式来做到这一点 - 只需将 marker 指向 bytes 的第一个字节。我试图找到这样的东西:
BitConverter.To<Marker>(bytes);
如何通过一次操作将字节数组转换为联合结构?
【问题讨论】:
标签: c# struct type-conversion byte union