using System; using System.Reflection; namespace _1_反射 { class Program { static void Main(string[] args) { Type t = typeof(Ss); foreach (object item in t.GetCustomAttributes(true))//获取类的特性 { MyClass myClass = item as MyClass; if (myClass!=null) { Console.WriteLine(myClass.UserName); Console.WriteLine(myClass.UserMember); } } foreach (MethodInfo item in t.GetMethods())//获取方法 { foreach (Attribute i in item.GetCustomAttributes(true))//获取方法的特性 { MyClass myClass = i as MyClass; if (myClass!=null) { Console.WriteLine(myClass.UserName); Console.WriteLine(myClass.UserMember); } } } Console.ReadKey(); } } [AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)] public class MyClass:System.Attribute { private string userName; private string userMember; public string UserName { get { return userName; } } public string UserMember { get { return userMember; } } public MyClass(string userName,string userMember) { this.userName = userName; this.userMember = userMember; } } [MyClass("黎明","管理员")] class Ss { [MyClass("刘德华","歌星")] public void aa() { } } }View Code