2010-03-04 89 views
4

我读了关于属性和理解,他们可以进行以适用于不同的目标实体与你的代码 - (见Attribute Targets)。C#属性和属性定位/目标

所以,看着的AssemblyInfo.cs文件在我的项目,我可以看到以下内容:

[assembly: AssemblyTitle("AttributesDemo")] 
[assembly: AssemblyDescription("")] 

这对我来说很有意义。目标是程序集的属性。

在我的代码,我可以如下类上添加一个属性:

[MyAttribute] 
class MySerialzableClass 
{ 

随着MyAttribute之中:

[AttributeUsage (AttributeTargets.All)] 
public class MyAttribute : System.Attribute 
{ 
} 

所以,我在第一码思考assembly:声明块。而且试过,只是实验:

[class: MyAttribute] 
class MySerialzableClass 
{ 

这使编译器警告:

“类”是无法识别的属性 位置。该块 中的所有属性都将被忽略。

所以我的问题是这样的 - 为什么必须在某些属性上指定属性目标并且不需要或不允许其他人使用?此外,你必须做到这一点?

回答

5

如果目标未在代码中表示,您必须明确指定目标。我知道只有三个目标,装配,模块和回报:

[return: MyAttribute] 
public static int meth(

类指定类:过多时,编译器能明白你的意思

+0

+1提*其他*例外。 – 2010-03-04 16:12:56

+0

+1并接受答案,虽然不应该是'ReturnValue:',而不是'Return:' – 2010-03-05 16:13:19

+0

否:)只需编写并尝试编译即可。 – Andrey 2010-03-05 16:21:43

3

正常情况下,属性会在其影响之前发生,如类或方法。对于程序集范围的属性,没有“之前”,所以你必须指定。

4

您可以为任何属性使用指定attribute targets,但只那些没有默认值的(assemblymodule)是强制性的。此外,如果您要将属性应用于非默认目标,则您必须使用这些注释。非默认目标

例子:

[return: MyAttribute] 
public int Method() { ... } 

public int Property { 
    get; 
    [param: MyAttribute] // applies to the parameter to the setter 
    set; 
} 

在你的榜样,正确的目标(这是默认值)是type

[type: MyAttribute] 
class MySerialzableClass { } 
+1

这是最好的答案,因为它提供了正确的目标关键字'type:'。可能的全局目标是'assembly'和'module',非全局目标是'field','event','method','param','property','return'和'type'。 – 2013-06-30 22:04:40