反射备忘2

定义代码

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类型来获取相应的信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值