您可以使用
sizeof运算符或
SizeOf函数。
这些选项之间有一些差异,请参阅参考链接。
无论如何,使用该函数的一种好方法是拥有一个通用方法或扩展方法,如下所示:
static class Test{ static void Main() { //This will return the memory usage size for type Int32: int size = SizeOf<Int32>(); //This will return the memory usage size of the variable 'size': //Both lines are basically equal, the first one makes use of ex. methods size = size.GetSize(); size = GetSize(size); } public static int SizeOf<T>() { return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); } public static int GetSize(this object obj) { return System.Runtime.InteropServices.Marshal.SizeOf(obj); }}


