定义代码
using System; using System.Collections.Generic; using System.Text; namespace CSharp语法复习 { [AttributeUsage(AttributeTargets.All,AllowMultiple=true,Inherited=true)] public class Memorial:Attribute { string _Remark; string _CreateTime; public Memorial(string remark, string createtime) { _Remark = remark; _CreateTime = createtime; } public string Remark { get { return _Remark; } } public string CreateTime { get { return _CreateTime; } } } [Memorial("这个是放在类上的", "1987-1-1")] class ReflectionTest { string _FirstThing; string _SecondThing; string _ThirdThing; string _FourThing; string _FifthThing; [Memorial("没有参数的构造函数","1987-1-1")] public ReflectionTest() { } [Memorial("有一个参数的构造函数","2010-11-11")] public ReflectionTest(string first) { _FirstThing = first; } [Memorial("FirstThing事件","2010-12-12")] public string FirstThing { get { return _FirstThing; } } [Memorial("FirstThing事件", "2010-12-12")] public string Test() { return "Test"; } } }
调用代码
Type type = typeof(ReflectionTest); Attribute[] attribute = Attribute.GetCustomAttributes(type); foreach (Memorial m in attribute) { Console.WriteLine("Remark:{0} CreateDateTime:{1}", m.Remark, m.CreateTime.ToString()); } MethodInfo[] myMethodInfo = type.GetMethods(); foreach (MethodInfo mif in myMethodInfo) { object[] attr = mif.GetCustomAttributes(typeof(Memorial), true); foreach (Memorial m in attr) { Console.WriteLine("Remark:{0} CreateDateTime:{1}", m.Remark, m.CreateTime.ToString()); } } ConstructorInfo[] myConstructorInfo = type.GetConstructors(); foreach (ConstructorInfo mif in myConstructorInfo) { object[] attr = mif.GetCustomAttributes(typeof(Memorial), true); foreach (Memorial m in attr) { Console.WriteLine("Remark:{0} CreateDateTime:{1}", m.Remark, m.CreateTime.ToString()); } } PropertyInfo[] myPropertyInfo = type.GetProperties(); foreach (PropertyInfo mif in myPropertyInfo) { object[] attr = mif.GetCustomAttributes(typeof(Memorial), true); foreach (Memorial m in attr) { Console.WriteLine("Remark:{0} CreateDateTime:{1}", m.Remark, m.CreateTime.ToString()); } }
结果:
Remark:FirstThing事件 CreateDateTime:2
Remark:这个是放在类上的 CreateDateTime:1987-1-1
------------
Remark:FirstThing事件 CreateDateTime:2010-12-12
------------
Remark:没有参数的构造函数 CreateDateTime:1987-1-1
Remark:有一个参数的构造函数 CreateDateTime:2010-11-11
------------
010-12-12
------------
小结:
要查看一个对象的自定义属性类,主要通过语句typeof(你要操作的类) 来返回该类的Type类型。
然后就能通过操作该Type类型来获取相应的信息