以下为本次实践代码:
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 }
时间: 2024-10-09 10:30:57