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

来源:互联网 发布:淘宝机器人 编辑:程序博客网 时间:2024/05/17 09:31
 

 

要用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 privateint field;
4 publicint Field
5 {
6 get
7 {
8 returnthis.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));
原创粉丝点击