C#反射技术之一动态读取和设置对象的属性值

 

 

要用C#反射技术的话,首先得引入System.Reflection 命名空间,这个命名空间里的类,具有动态加载程序集、类型,动态调用方法、设置和取得属性和字段的值、可以获取类型和方法的信息的功能。
要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的Type,微软已经为我们提供了足够多的方法。
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 Class MyClass
2 {
3 private int field;
4 public int Field
5 {
6 get
7 {
8 return this .field;
9 }
10 set
11 {
12 this .field = value;
13 }
14 }
15 }
如果有个这个类型的实例:
MyClass myObj = new MyClass();
我们要动态的为这个实例的属性
Field赋值,那么得先得到这个实例的类型:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> Type t = typeof (MyClass);
另一种方法是:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> Type t = myObj.GetType();
只要我们得到了对象的类型那么我们就可以利用反射对这个对象“为所欲为”了。
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> t.GetProperty( " Field " ).SetValue(myObj, 1 , null );
这样我们就为对象里的属性Field赋值了。如果把属性名和要赋的值写道配置文件里的话,我们就可以达到程序运行期间动态的为属性赋值了。
利用反射获取属性值的方法:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> int propValue = Convert.ToInt32(t.GetProperty( " Field " ).GetValue(myObj, null ));
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值