类型的sizeof()运算符

我通常会在我的C ++代码中执行此操作:

int variable = 10; int sizeOfVariable = sizeof(variable); //Returns 4 for 32-bit process 

但这对C#似乎不起作用。 有模拟吗?

C#中的sizeof运算符仅适用于编译时已知类型,而不适用于变量(实例)。

正确的例子是

 int variable = 10; int sizeOfVariable = sizeof(int); 

所以你可能正在寻找可以在任何对象实例或运行时类型上使用的Marshal.SizeOf

 int variable = 10; int sizeOfVariable = Marshal.SizeOf(variable); 

有关更多信息,请参见此处

.NET 4.0以后:

 if (Environment.Is64BitProcess) Console.WriteLine("64-bit process"); else Console.WriteLine("32-bit process"); 

旧版.NET Framework:

 public static bool Is64BitProcess { get { return IntPtr.Size == 8; } } 

从你的例子中我假设你想要这样做来确定过程的位数,这实际上可能不是你想要做的!)

您可以使用Marshal.SizeOf()方法,或在非托管代码中使用sizeof

 Console.WriteLine(Marshal.SizeOf(typeof(int))); 

这会在ideone上打印4

以下是Eric Lippert博客的链接,描述了两个sizeof选项之间的区别。

只有少数标准情况你会想要这样做:

 int x = sizeof(T) // where T is a generic type 

遗憾的是它不起作用:-)

 int x = Marshal.SizeOf(T) // where T is a generic type 

它确实有效,除了charboolMarshal.SizeOf(typeof(char)) == 1而不是2, Marshal.SizeOf(typeof(bool)) == 4而不是1)

 int x = sizeof(IntPtr); 

它不起作用,但你可以这样做

 int x = Marshal.SizeOf(typeof(IntPtr)); 

或更好

 int x = IntPtr.Size; 

所有其他基本类型( bytesbyteshortushortintuintlongulongfloatdoubledecimalboolchar )都有固定的长度,所以你可以做sizeof(int)并且它总是4。

您可以在不安全的上下文中对用户定义的结构使用sizeof ,但与Marshal.SizeOf不同,它不支持盒装对象