您不需要使用不安全的代码。建议使用 System.Runtime.InteropServices.Marshal.SizeOf()
例如:Marshal.SizeOf(new EmployeeStruct());
返回 16 而不是 12,因为内存中的默认包大小是 8。
因此对于:
struct EmployeeStruct
{
int empId; // 4 bytes
long salary; 8 bytes
}
//返回16而不是12(因为最小单位是8)
for:
struct EmployeeStruct
{
int empId; // 4 bytes
int empAge; // 4 bytes
long salary; 8 bytes
}
//也返回16
and for
struct EmployeeStruct
{
int empId; // 4 bytes
int empAge; // 4 bytes
int IdCompany; // 4 bytes
long salary; 8 bytes
}
返回 24 而不是 20(因为最小单位是 8)
我不知道你想要什么,但如果你需要每个字段大小的总和,你可以尝试使用这个函数:
public int SizeOf(Type t)
{
int s = 0;
var fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var f in fields)
{
var x = f.FieldType;
s += x.IsPrimitive ? Marshal.SizeOf(x) : SizeOf(x);
}
return s;
}
对于您的情况,它返回 12 而不是 16,您可以将它用于复杂的结构,例如:
struct EmployeeStruct
{
int field1; // 4 bytes
long field2; // 8 bytes
Person p; // 12 bytes
}
struct Person
{
int field1; // 4 bytes
long field2; // 8 bytes
}
SizeOf(typeof(EmployeeStruct) 将返回 24 而不是 32,但请记住,内存上的实际大小是 32,编译器使用 32 字节来分配内存。
Regards.