.NET DateTime 没有预定义的大小
由于 DateTime 是一个结构,其成员似乎分解为简单的数学值,因此我不确定为什么在其上使用 sizeof() 会产生问题标题中的消息。
Since DateTime is a struct with members that appear to break down into simple mathematical values, I'm not sure why using sizeof() on it produces the message in the question title.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为 CLR 只能在运行时确定大小...原因之一是“填充”(平台相关)...
参考。
另请参阅如何检查字节数被结构消耗?
Because the CLR can only determine the size at runtime... one of the reasons for this is "padding" (platform dependent)...
Ref.
see also How do I check the number of bytes consumed by a structure?
您得到的完整错误文本是:
因此,如果您确实使用
unsafe
上下文(请务必转到 C# 项目的“属性”、“构建”选项卡,并在“允许不安全代码”来编译下面的代码)它可以正常工作:使用
unsafe
关键字,sizeof()
将适用于所有enum
类型,并且与所有没有引用类型实例字段的 struct 类型(当然,DateTime 是没有引用类型成员的结构)。如果没有
unsafe
关键字,则无法使用sizeof
。 (但是,从 C# 2 开始,您可以在int
等预定义类型和enum
类型上使用它,但不能在DateTime
等其他结构上使用它。 code>,如您所见。)请注意,
DateTime
结构的特殊之处在于Marshal.SizeOf()
(或.NET 版本 4.5.1 (2013)) 之前的Marshal.SizeOf(typeof(DateTime))
将引发异常。这是因为不寻常的(对于struct
)结构布局“Auto”。The full error text you get, is:
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:With the
unsafe
keyword,sizeof()
will work with allenum
types and with allstruct
types that do not have instance fields of reference type (andDateTime
is a struct with no reference type members, for sure).Without the
unsafe
keyword, you cannot usesizeof
. (However, since C# 2 you are allowed to use it on pre-defined types likeint
and onenum
types, but not on other structs likeDateTime
, as you saw.)Note that the
DateTime
struct is exceptional in thatMarshal.SizeOf<DateTime>()
(orMarshal.SizeOf(typeof(DateTime))
prior to .NET version 4.5.1 (2013)) will throw an exception. This is because of the unusual (for astruct
) structure layout "Auto".Alex Pinsker 写了不错的解决方案 用于获取
DateTime
(或任何其他类型)的大小。Alex Pinsker wrote nice solution for getting the size of
DateTime
(or any other type).