C#在类外部实现对私有字段/私有属性的修改及调用

定义一个测试类:

1 class RefHero
2 {
3     string name = "Tom";
4     int age = 10;
5     bool isBoy = false;
6 
7     private string Address { set; get; }
8 
9 }

如果在外部想实现对私有字段的修改,该如何做呢?下面使用反射的技术实现这个需求,直接上代码:

 1 static void ModifyRefHeroFiled()
 2 {
 3     //收集需要修改的私有字段的名字
 4     string Filed_name = "name";
 5     string Filed_age = "age";
 6     string Filed_isBoy = "isBoy";
 7 
 8     Type type = typeof(RefHero);
 9     RefHero hero = new RefHero();
10     //获取 RefHero 中所有的实例私有字段
11     FieldInfo[] fieldArray = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
12     foreach (FieldInfo filed in fieldArray)
13     {
14         string fileName = filed.Name;
15         if (Filed_name == fileName)
16             filed.SetValue(hero, "Jick");
17         else if (Filed_age == fileName)
18             filed.SetValue(hero, 18);
19         else if (Filed_isBoy == fileName)
20             filed.SetValue(hero, true);
21         Console.WriteLine(string.Format("字段名字:{0} 字段类型:{1} 值 = {2}", filed.Name, filed.MemberType, filed.GetValue(hero)));
22     }
23 }

运行结果:

这篇文章中也有对 filed.SetValue() 方法的一个使用,只不过是使用在unity工程中:

https://www.cnblogs.com/luguoshuai/p/12775902.html

如果在外部想实现对私有属性的修改及调用,又该如何做呢?直接上代码:

 1 static void ModifyRedHeroProperty()
 2 {
 3     Type type = typeof(RefHero);
 4     RefHero hero = new RefHero();
 5     PropertyInfo[] pInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
 6     foreach (PropertyInfo info in pInfos)
 7     {
 8         Console.WriteLine("属性名:{0}
", info.Name);
 9         MethodInfo getInfo = info.GetGetMethod(true);
10         Console.WriteLine("get方法的名称{0} 返回值类型: {1} 参数数量: {2} MSIL代码长度: {3} 局部变量数量: {4}
",
11             getInfo.Name,
12             getInfo.ReturnType,
13             getInfo.GetParameters().Length,
14             getInfo.GetMethodBody().GetILAsByteArray().Length,
15             getInfo.GetMethodBody().LocalVariables.Count);
16 
17         MethodInfo setInfo = info.GetSetMethod(true);
18         Console.WriteLine("set{0} 返回值类型: {1} 参数数量: {2} MSIL代码长度: {3} 局部变量数量: {4}
",
19             setInfo.Name,
20             setInfo.ReturnType,
21             setInfo.GetParameters().Length,
22             setInfo.GetMethodBody().GetILAsByteArray().Length,
23             setInfo.GetMethodBody().LocalVariables.Count);
24 
25         setInfo.Invoke(hero, new object[] { "哀牢山" });
26         object obj = getInfo.Invoke(hero, null);
27         Console.WriteLine("方法名:{0} 内部值:{1}", info.Name, obj);
28     }
29 }

运行结果:

对私有方法的调用,与属性类似,在此不再赘述。

参考文章:https://blog.csdn.net/sinat_23338865/article/details/83341829

原文地址:https://www.cnblogs.com/luguoshuai/p/12818363.html