被C#中的[]困扰了好一段时间了,碰巧今天看到一篇这样的文章,总算解决了心中的疑惑。
注意:要使用Attribute的对象,必须继承自Attribute类,命名要以Attribute结尾。
AttributeUsage有三个属性,我们可以把它放置在定制属性前面。第一个属性是:
◆ValidOn
通过这个属性,我们能够定义定制特性应该在何种程序实体前放置。一个属性可以被放置的所有程序实体在AttributeTargets enumerator中列出。通过OR操作我们可以把若干个AttributeTargets值组合起来。
◆AllowMultiple
这个属性标记了我们的定制特性能否被重复放置在同一个程序实体前多次。
◆Inherited
我们可以使用这个属性来控制定制特性的继承规则。它标记了我们的特性能否被继承。
代码示例:
namespace MyLib
{
[AttributeUsageAttribute(AttributeTargets.All)]
public class CustomAttribute:Attribute
{
public CustomAttribute(string attName,int attAge)
{
Name = attName;
Age = attAge;
Review = false;
}
public string Name { get; set; }
public int Age { get; set; }
public bool Review { get; set; }
}
[Custom("Simon",26,Review=true)]
public class Customer
{
public Customer()
{
System.Reflector.MemberInfo info = typeof(Customer);
CustomAttribute attribute = (CustomAttribute)Attribute.GetCustomAttribute(info, typeof(CustomAttribute));
if (attribute != null)
{
CustomName=attribute.Name;
CustomAge = attribute.Age;
Review = attribute.Review;
}
}
public string CustomName{get;set;}
public int CustomAge{get;set;}
public bool Review{get;set;}
}
}
调用:
Customer c = new Customer();
查看c的各属性值,然后注释掉[Custom()]这一段,结果一目了然。
说明:AttributeTargets
AttributeTargets.Class,它规定了Help特性只能被放在class的前面。这也就意味着下面的代码将会产生错误
[Customer]
public class MyClass{
[Customer] //Error
public static void ShowMessage(){
}
}