更新:2007 年 11 月
在某些情况下,属性的目标(即属性适用于的实体)显得不明确。例如,在以下方法声明中,SomeAttr 属性可以适用于方法或方法的返回值:
| C# | |
|---|---|
public class SomeAttr : System.Attribute { } [SomeAttr] int Method() { return 0; }  | |
这种情况在封送处理时经常出现。为解析多义性,C# 对于每种声明都有一组默认目标,而通过显式指定属性目标可重写这些目标。
| C# | |
|---|---|
// default: applies to method [SomeAttr] int Method1() { return 0; } // applies to method [method: SomeAttr] int Method2() { return 0; } // applies to return value [return: SomeAttr] int Method3() { return 0; }  | |
请注意,这与 SomeAttr 被定义为有效的目标无关;也就是说,即使 SomeAttr 被定义为只适用于返回值,也必须指定 return 目标。换言之,编译器将不使用 AttributeUsage 信息解析不明确的属性目标。有关更多信息,请参见 AttributeUsage(C# 编程指南)。
属性目标的语法如下:
[target : attribute-list]
参数
下表列出了允许属性的所有声明。对于每个声明,声明中属性的可能目标在第二列中列出。以粗体显示的目标是默认值。
声明  | 可能的目标  | 
|---|---|
程序集  | assembly  | 
模块  | module  | 
类  | type  | 
结构  | type  | 
接口  | type  | 
枚举  | type  | 
委托  | type、return  | 
方法  | method、return  | 
参数  | param  | 
字段  | field  | 
属性 — 索引器  | property  | 
属性 — get 访问器  | method、return  | 
属性 — set 访问器  | method、param、return  | 
事件 — 字段  | event、field、method  | 
事件 — 属性  | event、property  | 
事件 — 添加  | method、param  | 
事件 — 移除  | method、param  | 
程序集级属性和模块级属性没有默认目标。有关更多信息,请参见
示例
| C# | |
|---|---|
using System.Runtime.InteropServices;
 | |
| C# | |
|---|---|
[Guid("12345678-1234-1234-1234-123456789abc"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface ISampleInterface { [DispId(17)] // set the DISPID of the method [return: MarshalAs(UnmanagedType.Interface)] // set the marshaling on the return type object DoWork(); }  | |