[C#]通过反射访问类私有成员

时间:2022-01-09 06:11:01

参考链接:

https://www.cnblogs.com/adodo1/p/4328198.html

代码如下:

 using System;
using System.Reflection;
using UnityEngine; public static class ObjectExtension
{
//获取私有字段的值
public static T GetPrivateField<T>(this object instance, string fieldName)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
FieldInfo info = type.GetField(fieldName, flags);
return (T)info.GetValue(instance);
} //设置私有字段的值
public static void SetPrivateField(this object instance, string fieldName, object value)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
FieldInfo info = type.GetField(fieldName, flags);
info.SetValue(instance, value);
} //获取私有属性的值
public static T GetPrivateProperty<T>(this object instance, string propertyName)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
PropertyInfo info = type.GetProperty(propertyName, flags);
return (T)info.GetValue(instance, null);
} //设置私有属性的值
public static void SetPrivateProperty<T>(this object instance, string propertyName, object value)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
PropertyInfo info = type.GetProperty(propertyName, flags);
info.SetValue(instance, value, null);
} //调用私有方法
public static object CallPrivateMethod(this object instance, string methodName, params object[] param)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
MethodInfo info = type.GetMethod(methodName, flags);
return info.Invoke(instance, param);
}
} public class TestReflectionClass {
private int field;
private string Property { get; set; } public TestReflectionClass()
{
field = ;
Property = "a";
} private void SetValue(int field, string property)
{
this.field = field;
this.Property = property;
}
} public class TestReflection : MonoBehaviour { void Start ()
{
TestReflectionClass testClass = new TestReflectionClass(); print(testClass.GetPrivateField<int>("field"));//
print(testClass.GetPrivateProperty<string>("Property"));//a testClass.CallPrivateMethod("SetValue", , "b"); testClass.SetPrivateProperty<string>("Property", "c");
print(testClass.GetPrivateField<int>("field"));//
print(testClass.GetPrivateProperty<string>("Property"));//c
}
}