获取结构体成员中每个字段的偏移量
使用Marshal.OffsetOf
来查看结构体中每个字段的偏移量:
using System;
using System.Runtime.InteropServices;
public struct ExampleStruct
{
public byte b; // 1 byte
public short s; // 2 bytes
public int i; // 4 bytes
public long l; // 8 bytes
public float f; // 4 bytes
public double d; // 8 bytes
}
class Program
{
static void Main()
{
Type t = typeof(ExampleStruct);
Console.WriteLine($"Size of ExampleStruct: {Marshal.SizeOf<ExampleStruct>()} bytes");
Console.WriteLine("Offsets of fields:");
Console.WriteLine($"b: {Marshal.OffsetOf(t, "b")} bytes");
Console.WriteLine($"s: {Marshal.OffsetOf(t, "s")} bytes");
Console.WriteLine($"i: {Marshal.OffsetOf(t, "i")} bytes");
Console.WriteLine($"l: {Marshal.OffsetOf(t, "l")} bytes");
Console.WriteLine($"f: {Marshal.OffsetOf(t, "f")} bytes");
Console.WriteLine($"d: {Marshal.OffsetOf(t, "d")} bytes");
}
}
标签:Console,bytes,偏移量,public,获取,字段,WriteLine,OffsetOf,Marshal
From: https://www.cnblogs.com/zhuoss/p/18401799