要用C#反射技术的话,首先得引入System.Reflection 命名空间,这个命名空间里的类,具有动态加载程序集、类型,动态调用方法、设置和取得属性和字段的值、可以获取类型和方法的信息的功能。
要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的Type,微软已经为我们提供了足够多的方法。
MyClass myObj = new MyClass();
我们要动态的为这个实例的属性 Field赋值,那么得先得到这个实例的类型:
利用反射获取属性值的方法:
要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的Type,微软已经为我们提供了足够多的方法。
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->
如果有个这个类型的实例:
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 }
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 = 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/
--> 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/
--> t.GetProperty( " Field " ).SetValue(myObj, 1 , null );
利用反射获取属性值的方法:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> int propValue = Convert.ToInt32(t.GetProperty( " Field " ).GetValue(myObj, null ));
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> int propValue = Convert.ToInt32(t.GetProperty( " Field " ).GetValue(myObj, null ));