검색결과 리스트
union에 해당되는 글 1건
- 2016.02.15 [.NET] C#에서의 공용체
C#은 공용체를 지원하지 않지만 StructLayout(LayoutKind.Explicit) 과 FieldOffset을 사용해서 공용체를 구현할 수 있다.
using System;
using System.Runtime.InteropServices;
public class UnionTest
{
public static void Main()
{
var bytes = new TBytes();
bytes.Word = 0x12345678;
Console.WriteLine("{0:x}", bytes.Byte0); // 78
Console.WriteLine("{0:x}", bytes.Byte1); // 56
Console.WriteLine("{0:x}", bytes.Byte2); // 34
Console.WriteLine("{0:x}", bytes.Byte3); // 12
}
}
[StructLayout(LayoutKind.Explicit)]
public struct TBytes
{
[FieldOffset(0)]
public byte Byte0;
[FieldOffset(1)]
public byte Byte1;
[FieldOffset(2)]
public byte Byte2;
[FieldOffset(3)]
public byte Byte3;
[FieldOffset(0)]
public uint Word;
}
댓글