简体   繁体   中英

.NET DateTime Does Not Have a Predefined Size

由于DateTime是一个结构,其成员似乎分解为简单的数学值,我不确定为什么在它上面使用sizeof()会在问题标题中生成消息。

Because the CLR can only determine the size at runtime... one of the reasons for this is "padding" (platform dependent)...

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding .

Ref .

see also How do I check the number of bytes consumed by a structure?

The full error text you get, is:

error CS0233: 'System.DateTime' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)

So if you do use unsafe context (be sure to go to the C# project's "Properties", the "Build" tab, and set a check mark in "Allow unsafe code" to make the below compile) it works fine:

    static void Main()
    {
        int s;
        unsafe
        {
            s = sizeof(DateTime);
        }
        Console.WriteLine(s); // writes 8
    }

With the unsafe keyword, sizeof() will work with all enum types and with all struct types that do not have instance fields of reference type (and DateTime is a struct with no reference type members, for sure).

Without the unsafe keyword, you cannot use sizeof . (However, since C# 2 you are allowed to use it on pre-defined types like int and on enum types, but not on other structs like DateTime , as you saw.)


Note that the DateTime struct is exceptional in that Marshal.SizeOf<DateTime>() (or Marshal.SizeOf(typeof(DateTime)) prior to .NET version 4.5.1 (2013)) will throw an exception. This is because of the unusual (for a struct ) structure layout "Auto".

Alex Pinsker为获取DateTime (或任何其他类型)的大小编写了很好的解决方案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM