C#:在运行时获取值类型变量的大小? [英] C#: Getting size of a value-type variable at runtime?
问题描述
我知道C和C ++等语言允许在运行时使用sizeof()函数确定数据(结构,数组,变量...)的大小。我在C#中尝试过,显然不允许将变量放入sizeof()函数中,而只能输入定义(浮点数,字节,Int32,uint等),我应该怎么做?
I know languages such as C and C++ allow determining the size of data (structs, arrays, variables...) at runtime using sizeof() function. I tried that in C# and apparently it does not allow putting variables into the sizeof() function, but type defintions only (float, byte, Int32, uint, etc...), how am I supposed to do that?
实际上,我希望这种情况发生:
Practically, I want this to happen:
int x;
Console.WriteLine(sizeof(x)); // Output: 4
而不是:
Console.WriteLine(sizeof(int)); // Output: 4
我敢肯定有一些正常的方法可以在运行时获取数据大小在C#中,但google并没有提供太多帮助。.这是我最后的希望
I'm sure there's some normal way to get the size of data at runtime in C#, yet google didn't give much help.. Here it is my last hope
推荐答案
以查找任意变量 x
,在运行时可以使用 Marshal.SizeOf :
To find the size of an arbitrary variable, x
, at runtime you can use Marshal.SizeOf:
System.Runtime.InteropServices.Marshal.SizeOf(x)
如dtb所述,此函数返回编组后的变量的大小,但是根据我的经验,通常这就是您想要的大小,例如在纯托管环境中,变量的大小几乎没有兴趣。
As mentioned by dtb, this function returns the size of the variable after marshalling, but in my experience that is usually the size you want, as in a pure managed environment the size of a variable is of little interest.
这篇关于C#:在运行时获取值类型变量的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!