【问题标题】:Get attributes in order of declaration using reflection使用反射按声明顺序获取属性
【发布时间】:2015-01-10 23:14:23
【问题描述】:

类似于Get properties in order of declaration using reflection 我想按声明的顺序获取属性。显然,我指的是属性将AllowMultiple 设置为trueAttributeUsage

我想知道MemberInfo.GetCustomAttributesAttribute.GetCustomAttributes 是否保证任何排序(我在MSDN 中没有找到任何东西)。

【问题讨论】:

  • 我不确定任何地方都定义了这些的顺序;你可能还想看看GetCustomAttributesData,但这也不是明确的声明顺序

标签: c# reflection


【解决方案1】:

C# 语言规范在17.2 Attribute specification 中说:

在这样的列表中指定属性的顺序以及附加到同一程序实体的部分的排列顺序并不重要。

例如,属性规范[A][B][B][A][A, B][B, A] 是等价的。

所以编译器可以根据需要对它们重新排序,而检索属性的方法不能保证以任何顺序返回它们。

你当然可以使用workaround proposed in the question you link to,使用[CallerLineNumber]

【讨论】:

  • 所以,我想我必须在我的自定义属性中包含一个 Order 属性。谢谢。
猜你喜欢
  • 2014-04-13
  • 2011-06-27
  • 2023-03-07
  • 2013-05-07
  • 2011-05-26
  • 1970-01-01
  • 2011-06-28
  • 2014-08-04
相关资源
最近更新 更多