定義一個測試類:
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}\n", info.Name); 9 MethodInfo getInfo = info.GetGetMethod(true); 10 Console.WriteLine("get方法的名稱{0} 返回值類型: {1} 參數數量: {2} MSIL代碼長度: {3} 局部變量數量: {4}\n", 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}\n", 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