简体   繁体   English

使用反射按声明顺序获取属性

[英]Get attributes in order of declaration using reflection

Similar to Get properties in order of declaration using reflection I want to get attributes in the order of their declaration. 类似于使用反射按声明顺序获取属性,我想按其声明顺序获取属性。 Obviously, I'm referring to attributes having AllowMultiple set to true for their AttributeUsage . 显然,我指的是将AttributeUsage的AllowMultiple设置为trueAttributeUsage

I wonder if MemberInfo.GetCustomAttributes or Attribute.GetCustomAttributes guarantee any ordering (I haven't found anything in the MSDN). 我想知道MemberInfo.GetCustomAttributesAttribute.GetCustomAttributes是否保证任何排序(我在MSDN中找不到任何东西)。

The C# language specification says in 17.2 Attribute specification : C#语言规范在17.2属性规范中说:

The order in which attributes are specified in such a list, and the order in which sections attached to the same program entity are arranged, is not significant. 在这样的列表中指定属性的顺序以及排列在同一程序实体上的节的排列顺序并不重要。

For instance, the attribute specifications [A][B] , [B][A] , [A, B] , and [B, A] are equivalent. 例如,属性规范[A][B][B][A][A, B][B, A]是等效的。

So the compiler can re-order them as it wants, and the methods for retrieving attributes can't guarantee to return them in any order. 因此,编译器可以根据需要对它们进行重新排序,并且检索属性的方法不能保证以任何顺序返回它们。

You can of course use the workaround proposed in the question you link to , using [CallerLineNumber] . 当然,您可以使用[CallerLineNumber] 使用所链接问题中建议解决方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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