关于特性的实例
Posted jimtang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于特性的实例相关的知识,希望对你有一定的参考价值。
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 { }
以上是关于关于特性的实例的主要内容,如果未能解决你的问题,请参考以下文章