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 { }