结构System.DateTime
及其表亲System.DateTimeOffset
的结构布局类型设置为“自动”。这可以看作与:为什么System.DateTime结构的布局类型为Auto?
typeof(DateTime).IsAutoLayout /* true */
或:
typeof(DateTime).StructLayoutAttribute.Value /* Auto */
,或者它可以从其中声明了IL中可以看出:
.class public auto ansi serializable sealed beforefieldinit System.DateTime
¯¯¯¯
通常一个结构(即是一个.NET值类型不是枚举)用C#编写将有布局“顺序”(除非已应用StructLayoutAttribute
指定另一个布局)。
我通过一些常见的BCL程序集进行搜索,DateTime
和DateTimeOffset
是我在此布局中发现的唯一公开可见的结构。
有谁知道为什么DateTime
有这个不寻常的结构布局?
有趣的事实。有关'Auto'的文档说*运行时自动为非托管内存中的对象成员选择适当的布局。使用此枚举成员定义的对象不能在托管代码之外公开。试图这样做会产生一个异常。*也许这只用于强制使用托管代码。原因可能是在.NET历史中布局多次改变(只是一个假设)。更多:http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx – ZoolWay
'auto'似乎没问题,也许这个问题应该是为什么这么少的其他类型使用它。 –
@ZoolWay我也认为这些线。请注意,我们仍然可以在C#中使用'DateTime *'指针类型,并使用'unsafe'上下文,例如,此程序可以正常工作:'不安全 int [] memory = {123,456,789,333,666, 999,}; fixed(int * pointer =&memory [0]) { var pointer2 =(DateTime *)pointer; Console.WriteLine(pointer2-> DayOfWeek); pointer2 + = 2; Console.WriteLine(pointer2-> DayOfWeek); } }'。 –