#region 程序集 ClassLibrary2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
#endregion
using System;
using System.Reflection;
namespace ClassLibrary2;
public static class Class1
{
//访问私有字段
public static T GetPrivateField<T>(this object instance, string fieldname)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
FieldInfo field = type.GetField(fieldname, bindingAttr);
return (T)field.GetValue(instance);
}
//访问私有属性
public static T GetPrivateProperty<T>(this object instance, string propertyname)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(propertyname, bindingAttr);
return (T)property.GetValue(instance, null);
}
//修改私有字段
public static void SetPrivateField(this object instance, string fieldname, object value)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
FieldInfo field = type.GetField(fieldname, bindingAttr);
field.SetValue(instance, value);
}
//修改私有属性
public static void SetPrivateProperty(this object instance, string propertyname, object value)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
PropertyInfo property = type.GetProperty(propertyname, bindingAttr);
property.SetValue(instance, value, null);
}
//访问私有方法
public static T CallPrivateMethod<T>(this object instance, string name, params object[] param)
{
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
Type type = instance.GetType();
MethodInfo method = type.GetMethod(name, bindingAttr);
return (T)method.Invoke(instance, param);
}
}
上面代码 摘自 网上。如有不适,即删!
1, 可把代码编译为 DLL,
2,在自己的工程中引入
3,调用。
已测试成功。