//创建用户自定义属性 [System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)] //用户自定义属性继承System.Attribute public class Author : System.Attribute { public string name; public double version; public Author(string name) { this.name = name; version = 1.0; } public string GetName() { return name; } } [Author("luokuan", version = 2.0)] public class MyBook { } //t当前实例 public static void PrintAttribute(System.Type t) { //通过反射获取用户自定义属性 System.Attribute[] arrs = System.Attribute.GetCustomAttributes(t); //循环出所的用户自定义属性 foreach (System.Attribute attribute in arrs) { if (attribute is Author) { Author au = attribute as Author; Console.WriteLine("Name is {0}: version is {1}", au.GetName(),au.version); } } }
自定义属性
最新推荐文章于 2022-08-30 16:30:34 发布