应用属性
更新:2007 年 11 月
通过下列过程将属性应用到代码元素。
通过从 .NET Framework 导入属性的命名空间来定义新的属性或使用现有属性。
通过在紧邻代码元素之前放置属性来将该属性应用于代码元素。
每种语言都有自己的属性语法。在 C++ 和 C# 中,属性由方括号括起来,并且通过空白(可包括换行符)与元素分隔。在 Visual Basic 中,属性由尖括号括起来,并且必须处于同一逻辑行;如果需要加换行符,则可以使用行继续字符。在 J# 中,使用特殊注释语法附加属性。
为属性指定位置参数和命名参数。
位置参数是必需的,并且必须放在所有命名参数之前;位置参数对应于属性的构造函数之一的参数。命名参数是可选的,对应于属性 (Attribute) 的读/写属性 (Property)。在 C++、C# 和 J# 中,为每个可选参数指定 name=value,其中 name 是属性的名称。在 Visual Basic 中,指定 name:=value。
属性在您编译代码时被发送到元数据中,并可通过运行库反射服务用于公共语言运行库以及任何自定义工具或应用程序。
按照约定,所有属性名都以 Attribute 结尾。但是,某些以运行库为目标的语言(如 Visual Basic 和 C#)不要求指定属性的全名。例如,如果要初始化 System.ObsoleteAttribute,只需将其引用为 Obsolete 即可。
将属性应用于方法
下面的代码示例显示如何声明 System.ObsoleteAttribute,该属性将代码标记为过时。字符串 "Will be removed in next version" 被传递到该属性。当调用该属性所描述的代码时,该属性将产生编译器警告以显示所传递的字符串。
using System;
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
{
static void Main()
{
// This generates a compile-time warning.
int i = Example.Add(2, 2);
}
}
using namespace System;
public ref class Example
{
public:
// Specify attributes between square brackets in C++.
// This attribute is applied only to the Add method.
[Obsolete("Will be removed in next version ")]
static int Add(int a, int b)
{
return (a + b);
}
};
void main()
{
// This generates a compile-time warning.
int i = Example::Add(2, 2);
return;
}
Imports System
Public Class Example
' Specify attributes between angle brackets in Visual Basic,
' and keep them on the same logical line.
' This attribute is applied only to the Add method.
<Obsolete("Will be removed in next version ")> _
Public Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Class
Module Test
Sub Main()
' This generates a compile-time warning.
Dim i As Integer = Example.Add(2, 2)
End Sub
End Module
import System.*;
public class Example
{
// Specify attributes with comment syntax in J#.
// This attribute is applied only to the Add method.
/** @attribute 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 MyInt = Example.Add(2,2);
}
}
在程序集级别应用属性
如果要在程序集级别应用属性,请使用 Assembly 关键字。下列代码显示在程序集级别应用的 AssemblyNameAttribute。
using System.Reflection;
[assembly:AssemblyName("MyAssembly")]
using namespace System::Reflection;
[assembly:AssemblyName("MyAssembly")]
Imports System.Reflection
<Assembly:AssemblyName("MyAssembly")>
import System.Reflection.*;
/** @assembly AssemblyName("MyAssembly") */
应用该属性时,字符串 "MyAssembly" 被放到文件元数据部分的程序集清单中。可以使用 MSIL 反汇编程序 (Ildasm.exe) 或通过创建检索该属性的自定义程序来查看该属性。