首页 > Windows开发 > 详细

访问私有成员的方法-------C# 转载

时间:2015-11-05 00:18:45      阅读:394      评论:0      收藏:0      [点我收藏+]
  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);
}

 

访问私有成员的方法-------C# 转载

原文:http://www.cnblogs.com/xiaoleye/p/4937682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!