ASP.NET Lab

The Best Web, The Best Future

博客园 首页 新随笔 订阅 管理

.NET Framework 允许开发者创造新的声明信息、为不同的程序实体指定声明的信息,并且从运行时环境中获取特性信息。例如,一个框架可能定义了一个能够被存放到程序元素(如类与方法)中来提供程序元素的说明文档映射的 HelpAttribute 特性。新的声明信息是通过特性类的声明而被定义的,并且还可能拥有被命名的位置参数。关于特性的更多信息,请参考:[编写自定义特性]。

下列规则概述了特性类的使用指南:

  • 在自定义特性类的名称中使用后缀 Attribute,如下范例所示。

    Visual Basic
    Public Class ObsoleteAttribute{}
    C#
    public class ObsoleteAttribute{}
  • 为你的特性而指定 AttributeUsage 来定义它们的准确用法,如下范例所示。

    Visual Basic
    <AttributeUsage(AttributeTargets.All, Inherited := False, AllowMultiple := True)>  _
    
    Public Class ObsoleteAttribute
       Inherits Attribute
       ' 在这里插入代码。
    End Class
    C#
    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    public class ObsoleteAttribute: Attribute {}
  • 尽可能地密封特性类,因此这些类不能够被派生。
  • 为必需的参数而使用位置参量(构造器参数)。与每个位置参量一样,以相同的名称来提供一个只读的属性,但是需要改变字母的大小写来区分它们之间的区别。这允许在运行时能够对参量进行访问。
  • 为可选的参数而使用被命名的参量(可读写的属性)。与每个被命名的参量一样,以相同的名称来提供一个可读写的属性,但是需要改变字母的大小写来区分它们之间的区别。
  • 不要同时以被命名的参量与位置参量来定义同一个参数。下列代码范例就说明了这个模式。

    Visual Basic
    Public Class NameAttribute
       Inherits Attribute
       Private userNameValue as String
       Private ageValue as Integer
    
       ' 这是一个位置参量。
       Public Sub New(userName As String) 
          userNameValue = userName
       End Sub
       
       Public ReadOnly Property UserName() As String
          Get
             Return userNameValue 
          End Get
       End Property
       
       ' 这是一个被命名的参量。
       Public Property Age() As Integer
          Get
             Return ageValue 
          End Get
          Set
             ageValue = value
          End Set 
       End Property
    End Class
    C#
    public class NameAttribute: Attribute 
    {
       string userName;
       int age;
    
       // 这是一个位置参量。
       public NameAttribute (string userName) 
       { 
           this.userName = userName;
       }
       public string UserName 
       { 
          get 
          {
             return userName; 
          }
       }
       // 这是一个被命名的参量。
       public int Age 
       { 
          get 
          {
             return age;
          }
          set 
          {
             age = value;
          }
       } 
    }
posted on 2007-02-04 15:39  Laeb  阅读(500)  评论(0编辑  收藏  举报