結構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); } }'。 –