访问私有成员的方法-------C# 转载
static void Main(string[] args) { MyClass mc = new MyClass(); Type t = mc.GetType(); Console.WriteLine("字段:"); foreach (FieldInfo fi in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) Console.WriteLine("名称:" + fi.Name + ",类型:" + fi.FieldType.Name); Console.WriteLine("属性:"); foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { //获取值 Console.WriteLine("名称:" + pi.Name + ",类型:" + pi.PropertyType.Name + ",值:" + pi.GetValue(mc, null)); pi.SetValue(mc, "nihao", null); //赋值 } Console.WriteLine("方法:"); foreach (MethodInfo mi in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) Console.WriteLine("名称:" + mi.Name + ",返回类型:" + mi.ReturnType.Name); Console.ReadKey(); } class MyClass { private int i; public int I; private string s; public string S { get { return s; } set { s = value; } } public void Method() { } }
1、得到私有字段的值: public static T GetPrivateField<T>(this object instance, string fieldname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); return (T)field.GetValue(instance); }2、得到私有属性的值: public static T GetPrivateProperty<T>(this object instance, string propertyname) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); return (T)field.GetValue(instance, null); }3、设置私有成员的值: public static void SetPrivateField(this object instance, string fieldname, object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); FieldInfo field = type.GetField(fieldname, flag); field.SetValue(instance, value); } 4、设置私有属性的值: public static void SetPrivateProperty(this object instance, string propertyname, object value) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); PropertyInfo field = type.GetProperty(propertyname, flag); field.SetValue(instance, value, null); } 5、调用私有方法: public static T CallPrivateMethod<T>(this object instance, string name, params object[] param) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic; Type type = instance.GetType(); MethodInfo method = type.GetMethod(name, flag); return (T)method.Invoke(instance, param); }