简体   繁体   中英

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 .

I wonder if MemberInfo.GetCustomAttributes or Attribute.GetCustomAttributes guarantee any ordering (I haven't found anything in the MSDN).

The C# language specification says in 17.2 Attribute specification :

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.

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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