Why does the System.DateTime struct have layout kind Auto?

隐身守侯 提交于 2019-11-30 01:13:58

问题


The struct System.DateTime and its cousin System.DateTimeOffset have their structure layout kinds set to "Auto". This can be seen with:

typeof(DateTime).IsAutoLayout    /* true */

or:

typeof(DateTime).StructLayoutAttribute.Value    /* Auto */

or it can be seen from the IL which declares:

.class public auto ansi serializable sealed beforefieldinit System.DateTime
              ¯¯¯¯

Normally a struct (that is a .NET value type which is not an enum) written with C# will have layout "Sequential" (unless a StructLayoutAttribute has been applied to specify another layout).

I searched through some common BCL assemblies, and DateTime and DateTimeOffset were the only publicly visible structs I found with this layout.

Does anyone know why DateTime has this unusual struct layout?


回答1:


This is going to require speculation, this decision was made a long time ago, well before .NET 1.0 shipped. The attribute on System.DateTime is at best a micro-optimization, not uncommon in .NET code. It is somewhat appropriate, the struct has only one field so there's never any issue with layout. The ones for the internal CustomAttribute structs were probably done by the same programmer. Doesn't matter either, unmanaged code never sees them.

The one for System.DateTimeOffset was done much later and almost certainly a copy-paste bug.

That programmer got away with it, no reason for the CLR to re-arrange the layout from the sequential version. Re-arranging with auto-layout occurs when the struct contains padding between fields that is large enough to fit another small field. Not the case for DateTimeOffet.

Some odds you'll get a Microsoft guru to pay attention to this when you file a feedback report for DateTimeOffset. It is wrong afaik. Post it to connect.microsoft.com



来源:https://stackoverflow.com/questions/21881554/why-does-the-system-datetime-struct-have-layout-kind-auto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!