Examples of Properties

 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 )]
     // Custom attribute class (program element (class or structure) that applies attributes, program elements can specify multiple attributes) 
    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
    {

    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325172301&siteId=291194637