使用以下过程将属性应用于代码的元素。
定义新属性或使用现有的 .NET 属性。
通过将属性立即置于元素前面,将属性应用于代码元素。
每种语言都有自己的属性语法。 在 C++ 和 C# 中,该属性由方括号括起来,并用空格分隔元素,其中包括换行符。 在 Visual Basic 中,特性用尖括号括起来,并且必须位于同一逻辑行上;如果需要换行,可以使用行续字符。
指定属性的位置参数和命名参数。
位置 参数是必需的,必须位于任何命名参数之前;它们对应于属性的构造函数之一的参数。 命名 参数是可选的,对应于属性的读/写属性。 在 C++ 和 C# 中,为每个可选参数指定
name=value
,其中属性name
的名称。 在 Visual Basic 中,指定name:=value
。
编译代码时,该属性将发出到元数据中,并且可通过运行时反射服务提供给公共语言运行时和任何自定义工具或应用程序。
按照约定,所有属性名称以“Attribute”结尾。 但是,面向运行时的多种语言(如 Visual Basic 和 C#)不需要指定属性的全名。 例如,如果要初始化 System.ObsoleteAttribute,只需将其引用为 已过时。
将属性应用于方法
下面的代码示例演示如何使用 System.ObsoleteAttribute,该代码将代码标记为已过时。 字符串 "Will be removed in next version"
将传递给属性。 当调用属性描述的代码时,此属性会导致编译器警告显示传递的字符串。
public class Example
{
// Specify attributes between square brackets in C#.
// This attribute is applied only to the Add method.
[Obsolete("Will be removed in next version.")]
public static int Add(int a, int b)
{
return (a + b);
}
}
class Test
{
public static void Main()
{
// This generates a compile-time warning.
int i = Example.Add(2, 2);
}
}
Public Class Example
' Specify attributes between square brackets in C#.
' This attribute is applied only to the Add method.
<Obsolete("Will be removed in next version.")>
Public Shared Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
End Class
Class Test
Public Shared Sub Main()
' This generates a compile-time warning.
Dim i As Integer = Example.Add(2, 2)
End Sub
End Class
在程序集级别应用属性
如果要在程序集级别应用属性,请使用 assembly
关键字(在 Visual Basic 中为 Assembly
)。 以下代码显示了 AssemblyTitleAttribute 应用于程序集级别。
using System.Reflection;
[assembly:AssemblyTitle("My Assembly")]
Imports System.Reflection
<Assembly: AssemblyTitle("My Assembly")>
应用此属性后,字符串 "My Assembly"
将放置在文件的元数据部分中的程序集清单中。 可以使用 IL 反汇编程序(Ildasm.exe) 查看属性,或者创建自定义程序来检索该属性。