特性使用指南

.NET Framework 使开发人员能够发明新的声明性信息类型、为各种程序实体指定声明性信息,以及在运行时环境中检索特性信息。 例如,框架可以定义一个可放置在程序元素(如类和方法)上的 HelpAttribute 特性,以提供从程序元素到其文档的映射。 新的声明性信息类型通过特性类的声明来定义,这些类可能有定位参数和命名参数。 有关特性的更多信息,请参见编写自定义特性

下面的规则概括了特性类的使用指南:

  • 将 Attribute 后缀添加到自定义特性类,如下面的示例所示。

    Public Class ObsoleteAttribute
    
    public class ObsoleteAttribute{}
    
  • 在特性上指定 AttributeUsage 以精确定义它们的用法,如下面的示例所示。

    <AttributeUsage(AttributeTargets.All, Inherited := False, AllowMultiple := True)>  _
    
    Public Class ObsoleteAttribute
       Inherits Attribute
       ' Insert code here.
    End Class
    
    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    public class ObsoleteAttribute: Attribute {}
    
  • 尽可能密封特性类,以便不能从它们派生类。

  • 为必需的参数使用定位参数(构造函数参数)。 提供与每个定位参数同名的只读属性,但更改大小写以将它们区分开。 这样就可以在运行时访问参数。

  • 对可选参数使用命名变量,并为每个命名变量提供读/写属性。

  • 不要同时用命名参数和定位参数来定义参数。 下面的代码示例阐释了这种模式。

    Public Class NameAttribute
       Inherits Attribute
       Private userNameValue as String
       Private ageValue as Integer
    
       ' This is a positional argument.
       Public Sub New(userName As String) 
          userNameValue = userName
       End Sub
    
       Public ReadOnly Property UserName() As String
          Get
             Return userNameValue 
          End Get
       End Property
    
       ' This is a named argument.
       Public Property Age() As Integer
          Get
             Return ageValue 
          End Get
          Set
             ageValue = value
          End Set 
       End Property
    End Class
    
    public class NameAttribute: Attribute 
    {
       string userName;
       int age;
    
       // This is a positional argument.
       public NameAttribute (string userName) 
       { 
           this.userName = userName;
       }
       public string UserName 
       { 
          get 
          {
             return userName; 
          }
       }
       // This is a named argument.
       public int Age 
       { 
          get 
          {
             return age;
          }
          set 
          {
             age = value;
          }
       } 
    }
    

部分版权所有 2005 Microsoft Corporation。 保留所有权利。

部分版权所有 Addison-Wesley Corporation。 保留所有权利。

设计指引的详细信息,请参阅"框架设计准则: 公约、 成语和可重复使用的模式。网络图书馆"书 Krzysztof Cwalina 和布拉德 · 艾布拉姆斯,2005年艾迪生 - 韦斯利,发表。

请参见

概念

使用准则

其他资源

类库开发的设计准则