C# AttributeUsageAttribute浅析

来源:互联网 发布:atheros linux驱动 编辑:程序博客网 时间:2024/06/06 00:36

       前面(不允许链接,见我博客Attribute章节)的定制特性HelpAttribute可以应用于任何目标元素,如果我们希望它只应用于类类型或方法时怎么办呢?.NET Framework当然提供了这一方面的支持:System. AttributeUsageAttribute类。AttributeUsageAttribute是.NET Framework提供的一个定制特性,它主要是作用于其他定制特性来限制目标定制特性的作用目标。

 

先来看看一个语法示例:

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Class.Method|AttributeTargets.Field|AttributeTargets.Property,AllowMultiple=false, Inherited = true)]public sealed class AttributeUsageAttribute : Attribute

AttributeUsageAttribute的构造函数:

public AttributeUsageAttribute (AttributeTargets validOn,其他参数)

 

(1)validOn使用按位"或"运算符组合的一组值,用于指示哪些程序元素是有效的。可以是:程序集、字段、事件、方法、模块、参数、属性、返回值、类型。

(2)AllowMultiple 附加属性,它表示是否允许将定制特性的实例多次应用于同一个目标元素,指示元素中是否可存在属性的多个实例,默认为false

(3)Inherited 附加属性,它表示定制特性应用于基类时,是否将该特性同时应用于派生类及重写的的成员,默认为true。       声明新的Attribute要用AttributeUsageAttribute做些限定:

 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.ReturnValue | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]    public class CountryAttribute : Attribute    {        public CountryAttribute()        {        }        public CountryAttribute(string name)        {            this.Name = name;        }        public int PlayerCount { get; set; }        public string Name { get; set; }    }    [Country("China")]    [Country("America")]    public class Sportsman    {        public string Name { get; set; }        [Country(PlayerCount = 5)]        public virtual void Play()        {        }    }    public class Hoopster : Sportsman    {        public override void Play()        {        }    }


 

 

原创粉丝点击