以下为本次实践代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ConsoleTest { class Program { static void Main(string[] args) { //反射读取类私有属性 Person per = new Person("ismallboy", "20102100104"); Type t = per.GetType(); //获取私有方法 MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance); //访问无参数私有方法 string strTest = method.Invoke(per, null).ToString(); //访问有参数私有方法 MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance); object[] par = new object[2]; par[0] = "ismallboy"; par[1] = 2; string strTest2 = method2.Invoke(per, par).ToString(); //获取私有字段 PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance); //访问私有字段值 string value = field.GetValue(per).ToString(); //设置私有字段值 field.SetValue(per, "new Name"); value = field.GetValue(per).ToString(); } } /// <summary> /// 个人信息 /// </summary> class Person { private string Name { get; set; } private string StuNo { get; set; } public Person(string name, string stuNo) { this.Name = name; this.StuNo = stuNo; } private string GetStuInfo() { return this.Name; } private string GetValue(string str, int n) { return str + n.ToString(); } } }
如果使用dynamic的话,也可以如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ConsoleTest { class Program { static void Main(string[] args) { //反射读取类私有属性 dynamic per = new Person("ismallboy", "20102100104"); Type t = per.GetType(); //获取私有方法 MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance); //访问无参数私有方法 string strTest = method.Invoke(per, null); //访问有参数私有方法 MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance); object[] par = new object[2]; par[0] = "ismallboy"; par[1] = 2; string strTest2 = method2.Invoke(per, par); //获取私有字段 PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance); //访问私有字段值 string value = field.GetValue(per); //设置私有字段值 field.SetValue(per, "new Name"); value = field.GetValue(per); } } /// <summary> /// 个人信息 /// </summary> class Person { private string Name { get; set; } private string StuNo { get; set; } public Person(string name, string stuNo) { this.Name = name; this.StuNo = stuNo; } private string GetStuInfo() { return this.Name; } private string GetValue(string str, int n) { return str + n.ToString(); } } }
以上图片由“图斗罗”提供