所以编译一下代码会得到一个编译器错误。
using
System;
public class SomethingAttribute : Attribute
{
public SomethingAttribute(String str)
{
}
}
// Error
[Something( " abc " )]
[Something( " def " )]
class MyClass
{
}
public class SomethingAttribute : Attribute
{
public SomethingAttribute(String str)
{
}
}
// Error
[Something( " abc " )]
[Something( " def " )]
class MyClass
{
}
编译器显示:
AttributeUsage652.cs(12,2): error CS0579: 重复“Something”属性
为了解决这个问题,在AttributeUsage行上指出你希望这个属性能够多次被附着于给定的类型。一下代码能正常工作:
using
System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true )]
public class SomethingAttribute : Attribute
{
public SomethingAttribute(String str)
{
}
}
[Something( " abc " )]
[Something( " def " )]
class MyClass
{
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true )]
public class SomethingAttribute : Attribute
{
public SomethingAttribute(String str)
{
}
}
[Something( " abc " )]
[Something( " def " )]
class MyClass
{
}
(PS:其实这个代码还是不能编译的,自己加上Main函数就可以运行了)