在.NET结构体设计准则中,它给出了结构体的最大合理大小为16字节。您如何确定您的结构体有多大,并且它是否受程序运行的体系结构的影响?这个值是仅适用于32位,还是两个架构都适用?
IntPtr
/UIntPtr
),那就更麻烦了 - 但这是相当罕见的。(正如Mehrdad所指出的,还有对齐填充的问题。)是的,结构体的大小受到架构的影响。C#中的结构体在32位系统中按4字节边界对齐,在64位系统中按8字节对齐。
例如:
struct Foo
{
int bar;
}
这个结构体在32位进程中占用4个字节,在64位进程中占用8个字节,即使“int bar”在32位和64位进程中都只占用4个字节。
更新:
我进行了一些测试。我编写了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
struct Bar
{
int a;
}
struct Foo
{
Uri uri;
int a;
}
class Program
{
static void Main(string[] args)
{
Foo[] foo;
long fooBefore = System.GC.GetTotalMemory(true);
foo = new Foo[10];
long fooAfter = System.GC.GetTotalMemory(true);
Bar[] bar;
long barBefore = System.GC.GetTotalMemory(true);
bar = new Bar[10];
long barAfter = System.GC.GetTotalMemory(true);
Foo aFoo = new Foo();
Bar aBar = new Bar();
System.Console.Out.WriteLine(String.Format("[Foo] Size of array of 10: {0}, Marshal size of one: {1}", fooAfter - fooBefore, System.Runtime.InteropServices.Marshal.SizeOf(aFoo)));
System.Console.Out.WriteLine(String.Format("[Bar] Size of array of 10: {0}, Marshal size of one: {1}", barAfter - barBefore, System.Runtime.InteropServices.Marshal.SizeOf(aBar)));
System.Console.ReadKey();
}
}
}
[Foo] Size of array of 10: 208, Marshal size of one: 16
[Bar] Size of array of 10: 88, Marshal size of one: 4
作为一个32位进程,我得到了这个输出:
[Foo] Size of array of 10: 92, Marshal size of one: 8
[Bar] Size of array of 10: 64, Marshal size of one: 4
观察结果: