我创建了一个包含两种值类型的简单结构。
public struct Identifier
{
public Guid ID { get; set; }
public Byte RequestType { get; set; }
}
然后我使用以下语句在自定义结构 Identifier
上调用了 Marshal.SizeOf()
方法。
Identifier i = new Identifier();
Console.WriteLine(Marshal.SizeOf(i)); // output: 20
Console.WriteLine(Marshal.SizeOf(i.GetType())); // output: 20
为什么 Marshal.SizeOf()
不返回 17?
以下说明说明一个 Guid
对象是 16 个字节,一个 Byte object
是 1 个字节。
Guid g = Guid.NewGuid();
Console.WriteLine(Marshal.SizeOf(g)); // output: 16
Console.WriteLine(Marshal.SizeOf(g.GetType())); // output: 16
Byte t = 0;
Console.WriteLine(Marshal.SizeOf(t)); // output: 1
Console.WriteLine(Marshal.SizeOf(t.GetType())); // output: 1
最佳答案
默认情况下,允许 CLR 重新排列(对于简单的结构它从不这样做)并根据需要填充结构。这通常是为了使其在内存中时与字边界对齐。
如果您不喜欢这种行为并想改变它,您可以指定不打包,如下所示:
[StructLayout(LayoutKind.Sequential,Pack=1)]
关于c# - 在仅包含值类型的自定义结构上使用 Marshal.SizeOf() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220999/