- 使用 Newtonsoft.Json 库将对象序列化成 JSON 字符串,然后计算字符串的长度。示例代码如下:
using Newtonsoft.Json;
using System.Text;
public static int CalculateObjectSize(object obj)
{
string json = JsonConvert.SerializeObject(obj);
return Encoding.UTF8.GetByteCount(json);
}
- 使用 System.Runtime.InteropServices.Marshal.SizeOf 泛型方法获取对象的大小。但需要注意,该方法只适用于结构体对象,且需要对每个对象类型单独调用。示例代码如下:
using System.Runtime.InteropServices;
public static int CalculateStructSize() where T : struct
{
return Marshal.SizeOf();
}
- 使用 Unsafe 类库的 sizeof 运算符获取一个非托管类型的大小。例如,使用该方法可获取一个字节数组的大小。示例代码如下:
using System.Runtime.CompilerServices;
using System;
public static int CalculateByteArraySize(byte[] bytes)
{
return Unsafe.SizeOf() * bytes.Length;
}