7 attributes custom-attributes
我想收集放置在Property上的所有自定义属性.分配给属性的同一类型有多个属性,但在收集它们时,结果集合仅包含特定类型的第一个属性:
Attribute类
[AttributeUsage(System.AttributeTargets.Property,
AllowMultiple = true)]
public class ConditionAttribute : Attribute{...}
Run Code Online (Sandbox Code Playgroud)
用法:
[ConditionAttribute("Test1")]
[ConditionAttribute("Test2")]
[ConditionAttribute("Test3")]
public Color BackColor{get; set;}
Run Code Online (Sandbox Code Playgroud)
现在循环遍历对象'value'的所有Props,其类包含Prop"BackColor":
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value))
{
foreach (Attribute attribute in property.Attributes)
{ ... }
....
}
Run Code Online (Sandbox Code Playgroud)
集合属性.属性只包含"ConditionAttribute"类型的一个属性:带有"Test1"的属性.其他人被忽略;-(
那么AllowMultiple不适用于属性属性吗?
提前致谢
亨里克
mcd*_*ski 19
根据MSDN上的帖子,这是设计为PropertyDescriptor类的一部分.
但是,您可以通过覆盖自定义属性中的TypeId来解决问题(感谢来自Mindscape的Ivan指出这一点):
public override object TypeId
{
get
{
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
是的,它确实有效。不知道为什么它不能通过 PropertyDescriptors 工作。
你总是可以这样做:Attribute.GetCustomAttributes(methodInfo, typeof(ConditionAttribute))