c# - 在仅包含值类型的自定义结构上使用 Marshal.SizeOf() 方法

标签 c# .net

我创建了一个包含两种值类型的简单结构。

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/

相关文章:

c# - 如何在 WPF 中围绕文本 block 的背景矩形定义描边?

c# - 获取DataPager控件中点击的页面数

c# - 是否有执行一系列超时的模式?

c# - 在 ASP.NET(C#) 中填充 GridView 时出现问题

c# - SQL 查询未检索到正确的结果

javascript - DIVstyle=none,但div仍然显示(用于弹出处理图形)

c# - 多对多映射未创建正确的表

c# - UseWindowsAzureActiveDirectoryBearerAuthentication 与 UseOpenIdConnectAuthentication 之间有什么区别?

c# - c# 代码的速度测试站点?

c# - 允许空值时如何将 nvarchar(x) 读入 String?