首页 > 其他 > 详细

关于特性的实例

时间:2018-05-03 00:41:40      阅读:323      评论:0      收藏:0      [点我收藏+]
 class Program
    {
        static void Main(string[] args)
        {
            PrintAuthorInfo(typeof(FirstClass));
            PrintAuthorInfo(typeof(SecoundClass));
            PrintAuthorInfo(typeof(ThreeClass));
            Console.ReadKey();
        }
        private static void PrintAuthorInfo(Type t)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(t);
           
            foreach (Attribute item in attrs)
            {
                if(item is Author)
                {
                    Author a = (Author)item;
                    Console.WriteLine($"{a.GetName()},{a.version}");
                }
            }
        }
    }
  [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple =true)]
    //自定义特性类(应用特性的程序元素(类或者结构),程序元素可以指定多个特性)
    public class Author:Attribute
    {
        string name;
        public double version;

        public Author(string name)
        {
            this.name = name;
            this.version = 1.0;
        }

        public string GetName() {
            return name;
        }
    }
 [Author("H.Ackerman")]
   public class FirstClass
    {

    }
    public class SecoundClass
    {

    }
    [Author("H.Ackerman"),Author("H.Knott",version =2.0)]
    public class ThreeClass
    {

    }

 

关于特性的实例

原文:https://www.cnblogs.com/jimtang/p/8983273.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!