访问私有成员的方法-------C# 转载
static void Main(string[] args) { MyClass mc = new MyClass(); Type t = mc.GetType(); Console.WriteLine("字段:"); foreach (FieldInfo fi in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) Console.WriteLine("名称:" + fi.Name + ",类型:" + fi.FieldType.Name); Console.WriteLine("属性:"); foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { //获取值 Console.WriteLine("名称:" + pi.Name + ",类型:" + pi.PropertyType.Name + ",值:" + pi.GetValue(mc, null)); pi.SetValue(mc, "nihao", null); //赋值 } Console.WriteLine("方法:"); foreach (MethodInfo mi in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) Console.WriteLine("名称:" + mi.Name + ",返回类型:" + mi.ReturnType.Name); Console.ReadKey(); } class MyClass { private int i; public int I; private string s; public string S { get { return s; } set { s = value; } } public void Method() { } }
1、得到私有字段的值: public static T GetPrivateField<T>(this object instance, string fieldname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); return (T)field.GetValue(instance); }2、得到私有属性的值: public static T GetPrivateProperty<T>(this object instance, string propertyname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); return (T)field.GetValue(instance, null); }3、设置私有成员的值: public static void SetPrivateField(this object instance, string fieldname, object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); field.SetValue(instance, value); } 4、设置私有属性的值: public static void SetPrivateProperty(this object instance, string propertyname, object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); field.SetValue(instance, value, null); } 5、调用私有方法: public static T CallPrivateMethod<T>(this object instance, string name, params object[] param) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); MethodInfo method = type.GetMethod(name, flag); return (T)method.Invoke(instance, param); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Sdcb Chats 技术博客:数据库 ID 选型的曲折之路 - 从 Guid 到自增 ID,再到
· 语音处理 开源项目 EchoSharp
· 《HelloGitHub》第 106 期
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 使用 Dify + LLM 构建精确任务处理应用