更新:2007 年 11 月
.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 和 Brad Abrams 编著、Addison-Wesley 于 2005 年出版的“Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries”(《框架设计指南:可重用 .NET 库的约定、术语和模式》)。