以下為本次實踐代碼:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Linq;
5 using System.Reflection;
6 using System.Text;
7 using System.Threading.Tasks;
8
9 namespace ConsoleTest
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 //反射讀取類私有屬性
16 Person per = new Person("ismallboy", "20102100104");
17 Type t = per.GetType();
18 //獲取私有方法
19 MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance);
20 //訪問無參數私有方法
21 string strTest = method.Invoke(per, null).ToString();
22 //訪問有參數私有方法
23 MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
24 object[] par = new object[2];
25 par[0] = "ismallboy";
26 par[1] = 2;
27 string strTest2 = method2.Invoke(per, par).ToString();
28
29 //獲取私有字段
30 PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
31 //訪問私有字段值
32 string value = field.GetValue(per).ToString();
33 //設置私有字段值
34 field.SetValue(per, "new Name");
35 value = field.GetValue(per).ToString();
36 }
37 }
38
39 /// <summary>
40 /// 個人信息
41 /// </summary>
42 class Person
43 {
44 private string Name { get; set; }
45 private string StuNo { get; set; }
46
47 public Person(string name, string stuNo)
48 {
49 this.Name = name;
50 this.StuNo = stuNo;
51 }
52
53 private string GetStuInfo()
54 {
55 return this.Name;
56 }
57
58 private string GetValue(string str, int n)
59 {
60 return str + n.ToString();
61 }
62 }
63 }
如果使用dynamic的話,也可以如下:
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Linq;
5 using System.Reflection;
6 using System.Text;
7 using System.Threading.Tasks;
8
9 namespace ConsoleTest
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 //反射讀取類私有屬性
16 dynamic per = new Person("ismallboy", "20102100104");
17 Type t = per.GetType();
18 //獲取私有方法
19 MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance);
20 //訪問無參數私有方法
21 string strTest = method.Invoke(per, null);
22 //訪問有參數私有方法
23 MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
24 object[] par = new object[2];
25 par[0] = "ismallboy";
26 par[1] = 2;
27 string strTest2 = method2.Invoke(per, par);
28
29 //獲取私有字段
30 PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
31 //訪問私有字段值
32 string value = field.GetValue(per);
33 //設置私有字段值
34 field.SetValue(per, "new Name");
35 value = field.GetValue(per);
36 }
37 }
38
39 /// <summary>
40 /// 個人信息
41 /// </summary>
42 class Person
43 {
44 private string Name { get; set; }
45 private string StuNo { get; set; }
46
47 public Person(string name, string stuNo)
48 {
49 this.Name = name;
50 this.StuNo = stuNo;
51 }
52
53 private string GetStuInfo()
54 {
55 return this.Name;
56 }
57
58 private string GetValue(string str, int n)
59 {
60 return str + n.ToString();
61 }
62 }
63 }