参考链接:
https://www.cnblogs.com/adodo1/p/4328198.html
代码如下:
1 using System; 2 using System.Reflection; 3 using UnityEngine; 4 5 public static class ObjectExtension 6 { 7 //获取私有字段的值 8 public static T GetPrivateField<T>(this object instance, string fieldName) 9 { 10 BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 11 Type type = instance.GetType(); 12 FieldInfo info = type.GetField(fieldName, flags); 13 return (T)info.GetValue(instance); 14 } 15 16 //设置私有字段的值 17 public static void SetPrivateField(this object instance, string fieldName, object value) 18 { 19 BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 20 Type type = instance.GetType(); 21 FieldInfo info = type.GetField(fieldName, flags); 22 info.SetValue(instance, value); 23 } 24 25 //获取私有属性的值 26 public static T GetPrivateProperty<T>(this object instance, string propertyName) 27 { 28 BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 29 Type type = instance.GetType(); 30 PropertyInfo info = type.GetProperty(propertyName, flags); 31 return (T)info.GetValue(instance, null); 32 } 33 34 //设置私有属性的值 35 public static void SetPrivateProperty<T>(this object instance, string propertyName, object value) 36 { 37 BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 38 Type type = instance.GetType(); 39 PropertyInfo info = type.GetProperty(propertyName, flags); 40 info.SetValue(instance, value, null); 41 } 42 43 //调用私有方法 44 public static object CallPrivateMethod(this object instance, string methodName, params object[] param) 45 { 46 BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; 47 Type type = instance.GetType(); 48 MethodInfo info = type.GetMethod(methodName, flags); 49 return info.Invoke(instance, param); 50 } 51 } 52 53 public class TestReflectionClass { 54 private int field; 55 private string Property { get; set; } 56 57 public TestReflectionClass() 58 { 59 field = 1; 60 Property = "a"; 61 } 62 63 private void SetValue(int field, string property) 64 { 65 this.field = field; 66 this.Property = property; 67 } 68 } 69 70 public class TestReflection : MonoBehaviour { 71 72 void Start () 73 { 74 TestReflectionClass testClass = new TestReflectionClass(); 75 76 print(testClass.GetPrivateField<int>("field"));//1 77 print(testClass.GetPrivateProperty<string>("Property"));//a 78 79 testClass.CallPrivateMethod("SetValue", 2, "b"); 80 81 testClass.SetPrivateProperty<string>("Property", "c"); 82 print(testClass.GetPrivateField<int>("field"));//2 83 print(testClass.GetPrivateProperty<string>("Property"));//c 84 } 85 }