Attribute

一、  简介:

 class Person   
    {
        [ReadOnly(true)] //只读
        [DisplayName("姓名")] //显示成中文
        [Browsable(false)] //不显示
        public int Age { get; set; }
        public string Name { get; set; }

        [Obsolete]  //标记成员已过时
        public void SayHi()
        {
            Console.WriteLine("大家好:我是{0},年龄{1}", Name, Age);
        }
    }

二、判断是否使用attribute及自定义:

   class Person   
    {
        [ReadOnly(true)] //只读
        [DisplayName("姓名")] //显示成中文
        [Browsable(false)] //不显示
        public int Age { get; set; }
        public string Name { get; set; }

        [Obsolete]
        public void SayHi()
        {
            Console.WriteLine("大家好:我是{0},年龄{1}", Name, Age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person();
            p1.Name = "chen";
            p1.Age = 22;
            Type type = p1.GetType();

            //查看标签是否有用
            object[] obsoltesAttrs = type.GetCustomAttributes(typeof(ObsoleteAttribute), false);
            if(obsoltesAttrs.Length>0)
            {
                Console.WriteLine("这个类已经过时");
            }
            else
            {
                Console.WriteLine("这个类没有过时");
            }

            //遍历属性
            foreach (PropertyInfo prop in type.GetProperties())
            {
                string displayName;
                //方式一
                DisplayNameAttribute display=(DisplayNameAttribute)prop.GetCustomAttribute(typeof(DisplayNameAttribute));
                if(display==null)
                {
                    displayName = null;
                }
                else
                {
                    displayName = display.DisplayName;
                }

                //方式二
                /*
                object[] diaplayAttrs = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
                if(diaplayAttrs.Length<=0)
                {
                    displayName = null;
                }
                else
                {
                    DisplayNameAttribute displayAttr = (DisplayNameAttribute)diaplayAttrs[0];
                    displayName = displayAttr.DisplayName;
                }
                */
                string name = prop.Name;
                object value = prop.GetValue(p1);
                Console.WriteLine(name +"("+ displayName + ")"+ "=" + value);
               // DisplayNameAttribute displayAttr = (DisplayNameAttribute)prop
            }
            Console.ReadKey();
        } 
        
    }
//自定义attribute
    public class JanpanDisplayAttribute : Attribute
    {

        public string DisplayName { get; set; }
        public JanpanDisplayAttribute(string name)
        {
            this.DisplayName = name;
        }
    }
   

猜你喜欢

转载自www.cnblogs.com/fuyouchen/p/9361404.html