如何通过反射访问嵌套私有类数组中的私有字段并修改值?
解决方案实现步骤
核心思路
逐层通过反射突破访问限制:先获取外层类的私有数组字段,再定位数组指定索引的元素,最后访问嵌套私有类的字段并修改值。
完整代码示例
首先是你提到的类结构(模拟定义):
namespace space1 { public class BigClass { private SmallClass[] CustomArrays = new SmallClass[] { new SmallClass { MyGoal = 16 }, new SmallClass { MyGoal = 17 } // 目标元素,加1后变为18 }; private class SmallClass { private int MyGoal; } } }
然后是反射实现的代码:
using System; using System.Reflection; class Program { static void Main() { // 1. 创建BigClass实例 var bigInstance = new space1.BigClass(); // 2. 获取BigClass的Type,定位私有字段CustomArrays Type bigType = typeof(space1.BigClass); FieldInfo customArraysField = bigType.GetField("CustomArrays", BindingFlags.Instance | BindingFlags.NonPublic); // 3. 获取数组对象,提取索引为1的元素(SmallClass实例) Array smallArray = (Array)customArraysField.GetValue(bigInstance); object targetSmallInstance = smallArray.GetValue(1); // 4. 获取私有嵌套类SmallClass的Type Type smallType = bigType.GetNestedType("SmallClass", BindingFlags.NonPublic); // 5. 定位SmallClass的私有字段MyGoal FieldInfo myGoalField = smallType.GetField("MyGoal", BindingFlags.Instance | BindingFlags.NonPublic); // 6. 获取字段值、加1后重新设置 int currentValue = (int)myGoalField.GetValue(targetSmallInstance); myGoalField.SetValue(targetSmallInstance, currentValue + 1); // 验证结果(可选) int updatedValue = (int)myGoalField.GetValue(targetSmallInstance); Console.WriteLine(updatedValue); // 输出18 } }
关键步骤解析
- 访问私有字段/嵌套类的核心:BindingFlags
必须指定BindingFlags.Instance | BindingFlags.NonPublic,才能让反射识别私有实例成员,缺任一标志都会导致找不到目标成员。 - 数组元素的提取
从CustomArrays字段拿到的是Array类型对象,直接用Array.GetValue(索引)即可定位到指定位置的元素,无需强制转换为具体数组类型(因为SmallClass是私有嵌套类,外部无法直接声明其数组类型)。 - 逐层突破访问限制
先从BigClass拿到数组,再从数组拿到SmallClass实例,最后从实例拿到MyGoal字段,每一步都用反射对应类型的成员信息来操作,确保每一层的私有访问权限都被正确处理。
内容的提问来源于stack exchange,提问作者holymoly
相关产品推荐
相关产品推荐

