C#访问私有方法,字段和属性
增加命名空间: using System.Reflection; 代码: public static class PrivateExtension { public static Object GetPrivateField(Object instance, String fieldname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); while (field == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; field = type.GetField(fieldname, flag); } return field.GetValue(instance); } public static Object GetPrivateProperty(Object instance, String propertyname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); while (field == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; field = type.GetProperty(propertyname, flag); } return field.GetValue(instance, null); } public static void SetPrivateField(Object instance, String fieldname, Object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); while (field == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; field = type.GetField(fieldname, flag); } field.SetValue(instance, value); } public static void SetPrivateProperty(Object instance, String propertyname, Object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); while (field == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; field = type.GetProperty(propertyname, flag); } field.SetValue(instance, value, null); } public static Object CallPrivateMethod(Object instance, String name, params Object[] param) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); MethodInfo method = type.GetMethod(name, flag); while (method == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; method = type.GetMethod(name, flag); } return method.Invoke(instance, param); } public static Object CallPrivateMethodEx(Object instance, String name, params Object[] param) { if (param == null || param.Length == 0) { return CallPrivateMethod(instance, name, param); } Type[] types = new Type[param.Length]; for (int i = 0; i < param.Length; i++) { types[i] = param[i].GetType(); } BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); MethodInfo method = type.GetMethod(name, flag,null,types,null); while (method == null && type.BaseType != null) { //访问基类,直到找到对应的字段或者属性或者方法 type = type.BaseType; method = type.GetMethod(name, flag, null, types, null); } return method.Invoke(instance, param); } }查看完整版本: C#访问私有方法,字段和属性
Tags: