除了定制attributes之外,可以使用Attributes属性定义如何使用这些属性。例如:

[AttributeUsage( 
    validon, 
    AllowMultiple = allowmultiple, 
    Inherited = inherited
)] 

强烈推荐使用AttributeUsage属性将属性文档化,因此属性的用户能直接使用已命名的属性,而不用在源代码中查找公用的读/写字段和属性。

定义属性目标

 1AttributeUsage属性public enum AttributeTargets
 2

当使用Attribute属性时,能指定AttributeTargets.all(属性目标),因此属性能被附加到在枚举AttributeTargets列出的任意类型上。若未指定AttributeUsage属性,缺省值是AttributeTargets.All。属性AttributeTargets用来限制属性使用范围。

 1AttributeUsage属性[AttributeUsage(AttributeTargets.Class)]
 2AttributeUsage属性public class RemoteObjectAttribute : Attribute
 3

 可以使用或(|)操作符组合属性目标枚举中列出的项。

 单一用途和多用途属性

可以使用AttributeUsage定义属性的单一用途或多用途。即确定在单个字段上使用单一属性的次数。在缺省情况下,所有属性都是单用途的。在AttributeUsage属性中,指定AllowMultipletrue,则允许属性多次附加到指定的类型上。例如:

 1AttributeUsage属性[AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
 2AttributeUsage属性public class SomethingAttribute : Attribute
 3

 

指定继承属性规则

   AttributeUsageAttribute属性的最后部分是继承标志,用于指定属性是否能被继承。缺省值是false。然而,若继承标志被设置为true,它的含义将依赖于AllowMultiple标志的值。若继承标志被设置为true,并且AllowMultiple标志是flag,则改属性将忽略继承属性。若继承标志和AllowMultiple标志都被设置为true,则改属性的成员将与派生属性的成员合并。范例:

 1AttributeUsage属性using System;
 2AttributeUsage属性using System.Reflection;
 3AttributeUsage属性
 4AttributeUsage属性namespace AttribInheritance
 5

 

AllowMultiple设置为false,结果是:

Custom Attribute: def

 AllowMultiple设置为true,结果是:

Custom Attribute: def

Custom Attribute: abc

相关文章:

  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
猜你喜欢
  • 2021-10-10
  • 2022-02-16
  • 2021-08-29
  • 2021-12-17
  • 2021-07-25
  • 2021-06-23
  • 2021-12-30
相关资源
相似解决方案