1
命名空间引入
2
3 using System.Reflection;
4
5 首先定义一个类
6
7 public class Dog
8 {
9 public string DogName { get ; set ; }
10
11 }
12
13 类的实例:
14
15 Dog mydog = new Dog();
16
17 获取实例类型
18
19 Type t = typeof (Dog);
20 或者Type t = mydog.GetType();
21
22 有了这个类型t,就可以利用反射对这个实例为所欲为了:
23
24 设置属性值:
25
26 t.GetProperty( " DogName " ).SetValue(mydog, " pet " , null );
27
28 获取属性值:
29
30 t.GetProperty( " DogName " ).GetValue(mydog, null ).ToString();
2
3 using System.Reflection;
4
5 首先定义一个类
6
7 public class Dog
8 {
9 public string DogName { get ; set ; }
10
11 }
12
13 类的实例:
14
15 Dog mydog = new Dog();
16
17 获取实例类型
18
19 Type t = typeof (Dog);
20 或者Type t = mydog.GetType();
21
22 有了这个类型t,就可以利用反射对这个实例为所欲为了:
23
24 设置属性值:
25
26 t.GetProperty( " DogName " ).SetValue(mydog, " pet " , null );
27
28 获取属性值:
29
30 t.GetProperty( " DogName " ).GetValue(mydog, null ).ToString();