using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace codeTest { class Program { static void Main(string[] args) { //通过反射来获取Attribute中的信息 MyAttribute myattribute; foreach (var attr in typeof(MyClass).GetCustomAttributes(true)) { myattribute = attr as MyAttribute; Console.WriteLine(myattribute.Name); } Console.ReadLine(); } } //自定义Attribute经常用到 AttributeUsage ,可以限制自定义Attribute的使用范围 [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] class MyAttribute : Attribute { //MyAttribute必须继承Attribute string name; public MyAttribute(string nameIn) { this.name = nameIn; } public string Name { get { return this.name; } } public string desc { get; set; } } //MyAttribute可以缩写为 My [My("MyAttribute",desc="MyClass")] class MyClass { } }
时间: 2024-10-26 09:39:57