如果 GetFields() 不能保证顺序,那么 LayoutKind.Sequential 如何工作

发布于 2024-12-14 12:27:17 字数 185 浏览 4 评论 0原文

我需要按照声明顺序的保证顺序获取字段信息。现在我正在使用属性来指定顺序。

有没有更自动的方法来做到这一点?

有谁知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柏林苍穹下 2024-12-21 12:27:17

如果您希望 Type.GetFields 返回的字段顺序保持稳定,请尝试按 MetadataToken 属性。

Type myType = ...
BindingFlags flags = ...
IEnumerable<FieldInfo> orderedFields = myType.GetFields(flags)
                                             .OrderBy(field => field.MetadataToken);

根据经验,已发现以这种方式排序字段按声明顺序返回它们尽管没有记录

顺便说一句,所提出的问题并不完全有意义;没有任何理由相信反射 API 与运行时如何在内存中布置对象有任何关系。

If you want the ordering of the fields returned by Type.GetFields to be stable, try sorting by the MetadataToken property.

Type myType = ...
BindingFlags flags = ...
IEnumerable<FieldInfo> orderedFields = myType.GetFields(flags)
                                             .OrderBy(field => field.MetadataToken);

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.

只是在用心讲痛 2024-12-21 12:27:17

这个问题很老但不是那么老......我现在正在处理同样的问题。我更喜欢按照声明的顺序获取字段。以下调用应适用于值类型或格式化引用类型。

var fields = type.GetFields().OrderBy(f => Marshal.OffsetOf(type, f.Name).ToInt32());

享受!

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.

var fields = type.GetFields().OrderBy(f => Marshal.OffsetOf(type, f.Name).ToInt32());

Enjoy!

哆兒滾 2024-12-21 12:27:17

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文