如果 GetFields() 不能保证顺序,那么 LayoutKind.Sequential 如何工作
我需要按照声明顺序的保证顺序获取字段信息。现在我正在使用属性来指定顺序。
有没有更自动的方法来做到这一点?
有谁知道 LayoutKind.Sequential 是如何工作的,以及我是否可以应用它的技术。
我不明白 LayoutKind.Sequential 是如何工作的,除非有一些添加属性的预编译器代码。
I need to get fieldinfo in a guaranteed order with respect to declaration order. Right now I'm using attributes to specify order.
Is there a more automatic way of doing this?
Does anyone have knowledge of how LayoutKind.Sequential
works, and if I can apply its technique.
I don't see how LayoutKind.Sequential
works, unless there's some precompiler code that adds attributes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望 Type.GetFields 返回的字段顺序保持稳定,请尝试按
MetadataToken
属性。根据经验,已发现以这种方式排序字段按声明顺序返回它们,尽管没有记录。
顺便说一句,所提出的问题并不完全有意义;没有任何理由相信反射 API 与运行时如何在内存中布置对象有任何关系。
If you want the ordering of the fields returned by
Type.GetFields
to be stable, try sorting by theMetadataToken
property.Empirically, ordering fields in this manner has been found to return them in declaration order, although this isn't documented.
By the way, the question as asked doesn't entirely make sense; there isn't any reason to believe that the reflection API is tied in any way to how the runtime lays objects out in memory.
这个问题很老但不是那么老......我现在正在处理同样的问题。我更喜欢按照声明的顺序获取字段。以下调用应适用于值类型或格式化引用类型。
享受!
The question is old but not so old... I'm dealing now with the same problem. And I prefer to get the fields in tho order of declaration. The following call should work for a value type or a formatted reference type.
Enjoy!
LayoutKind.Sequential 指定类型应按照源代码中声明的顺序在内存中布局。
如果没有该属性,CLR 可以通过重新排列字段来自由优化内存使用。
因此,该属性只是添加元数据,告诉 CLR 不要进行任何内存优化,从而扰乱字段的顺序。
LayoutKind.Sequential specifies that the fields of the type should be laid out in memory in the same order they are declared in your source code.
Without the attribute the CLR is free to optimize memory use by rearranging the fields.
So the attribute just adds metadata that tells the CLR not to do any in memory optimalisation that messes up the order of fields.