Does GetCustomAttributes() preserve the attribute order in .NET?

前端 未结 4 1413
-上瘾入骨i
-上瘾入骨i 2020-12-11 01:17

The title pretty much says it all. When I\'m doing some reflection through my classes, will the MemberInfo.GetCustomAttributes() method preserve the order of attributes on a

4条回答
  •  萌比男神i
    2020-12-11 01:35

    Unfortunately no, you cannot guarantee that the order will be the same as the order in which you specified them.

    Edit: a workaround

    Disclaimer: I apologize ahead of time if I am misunderstanding your ultimate problem.

    It sounds as if you need to be able to pass n number of strings to MenuItemAttribute and have MenuItemAttribute maintain the order of these strings as entered by the developer in the attributes constructor.

    Here is a possible solution:

    Have MenuItemAttribute use a LinkedList to maintain its state. Then you can iterate the params String[] in your constructor and add them to the LinkedList which would maintain the order.

提交回复
热议问题