对 C# 类中的属性进行排序 [英] Sequence the Properties in a C# Class

查看:147
本文介绍了对 C# 类中的属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要解析的文件格式如下:

We have a file format we need to parse that looks like:

v1|000|sammy|endpoint|blah

这是供应商提供给我们的有序固定宽度格式,因此这 5 个字段中的每一个都映射到类中的特定属性(实际格式有 >30 个).

It's an ordered fixed-width format a vendor provides to us, so each of those 5 fields maps to a specific property in the class (the actual format has >30).

我想通过将序列应用于属性来使用反射来解析它.我可以这样做的一种方法是自己编写一些东西 - 编写一个接受单个数字的 Attribute 类,并将该属性应用到每个属性及其序列索引,并在 OrderBy 子句中的反射期间查找它.

I'd like to just parse this with Reflection by applying sequence to the properties. One way I could do this is to just make something up myself - write an Attribute class that takes a single number, and apply that attribute to each property with its sequence index, and look for it during Reflection in the OrderBy clause.

在 C# 中是否有现有的或更好的方法来做到这一点?例如,是否已经有一个属性?有没有办法在 C# 甚至 MSIL 中询问在类中声明了什么顺序属性?

Is there an existing or better way to do this in C#? For example, is there already an Attribute for this? Is there a way to ask in C# or maybe even MSIL what order properties were declared in a class?

推荐答案

属性在元数据中的显示顺序使用 PropertyInfo.MetadataToken.碰巧的是,当前的编译器会使这个顺序与属性在源代码中出现的顺序相匹配,因此通过按 MetadataToken 排序,您可以获得与源代码中相同的顺序.

The order in which properties appear in the metadata is visible using PropertyInfo.MetadataToken. It so happens that the current compiler will make this order match the order in which properties appear in the source code, so by ordering by MetadataToken, you get the same order as in the source code.

免责声明:未来的编译器可能会改变这一点.如果没有理由,它可能不会,但如果编译器,例如,变成多线程,可能需要额外的不必要的努力来保留原始顺序.如果您依赖此方法,请确保在 .NET Framework 以这种方式进行更新时会出现硬错误而不是静默运行时损坏.

Disclaimer: a future compiler may change this. It probably won't if there's no reason for it, but if the compiler, for example, becomes multithreaded, it may take extra unnecessary effort to preserve the original order. If you rely on this, do make sure you get a hard error rather than silent runtime corruption if/when .NET Framework is updated in such a way that this breaks.

这篇关于对 C# 类中的属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆