初始C#中的Attribute类

来源:互联网 发布:我的世界0.15.4暮色js 编辑:程序博客网 时间:2024/06/06 14:10

 

 最近做项目过程中遇到了这个类,查了下MSDN,是这么说的。

 Attribute类:表示自定义属性的基类。

 看到了就有点蒙圈了,这到底是用来干什么的呢?

 

 Attribute类

 从网上查了一些资料后,就有点明白了,都说它就好比是一个附着物,用来定义额外的信息。举个例子说一下吧!我们做程序开发的时候,如何确定方法是谁开发的?当然你可以在方法上添加注释,用来表明这个方法是谁敲的,除此之外呢?还有其他方法吗?

 这时这个类就派上用场了。通过继承此类,可以自定义一个属性类,然后附加的形式来为需要添加的类或者方法添加额外的属性。


 Demo展示

 

<span style="font-family:SimSun;font-size:18px;"> /// <summary>    /// 自定义额外属性的类    /// </summary>    class ClassAttribute : Attribute    {        private string name { set; get; }        public ClassAttribute(string Name)        {            this.name = Name;        }    }</span>


 上面就是自定义额外属性的类,那么如何利用呢?

 

<span style="font-family:SimSun;font-size:18px;">  [Class("学生类",Age=12)]    class Student  ///默认第一个不赋值的为构造函数类型的赋值,走的是构造函数    {        [Class("Football")]        public string profession;        public string Profession        {            get { return profession; }            set { profession = value; }        }    }</span>


 就是这么简单通过打标签的形式,就可以为类、接口、方法等添加额外的属性。

 那么这时候,你可能会问,我已经添加了,那么如何来读取我添加的额外的属性呢?

 Attribute类有20多个GetCustomAttribute的方法,通过这个方法就可以读取定义的额外的属性。

<span style="font-family:SimSun;font-size:18px;"> static void Main(string[] args)        {                       //使用反射读取Attribute            System.Reflection.MemberInfo info = typeof(Student); //通过反射得到Student类的信息            ClassAttribute hobbyAttr = (ClassAttribute)Attribute.GetCustomAttribute(info, typeof(ClassAttribute));            if (hobbyAttr != null)            {                Console.WriteLine("学生年龄:{0}", hobbyAttr.Age);                       }          }</span>


 上面就是通过调用GetCustomAttribute的方法来读取自定义的额外的属性操作。下面来用一张图来总结一下。


 

 小结

 大家可以试想一下,从宏观上知道了此类的作用,以后那些地方可以用到,用起来更方便简洁。

 


0 0
原创粉丝点击