C#中访问私有成员详解

首先访问一个类的私有成员不是什么好做法。大家都知道私有成员在外部是不能被访问的。一个类中会存在很多私有成员:如私有字段、私有属性、私有方法。对于私有成员造访,可以套用下面这种非常好的方式去解决。

  1. private string name;  
  2. public string Name  
  3. {  
  4.     get 
  5.     {  
  6.         return name;  
  7.     }  
  8.     set 
  9.     {  
  10.         name = value;  
  11.     }  

但是有时候,源代码是别人的,只提供给你dll。或者你去维护别人的代码,源代码却有丢失。这样的情况或许你想知道私有成员的值,甚至去想直接调用类里面的私有方法。那怎么办呢?在.net中访问私有成员不是很难,这篇文章提供几个简单的方法让你如愿以偿。

 

为了让代码用起来优雅,使用扩展方法去实现。

1、得到私有字段的值:

  1. public static T GetPrivateField<T>(this object instance, string fieldname)  
  2. {  
  3.     BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;  
  4.     Type type = instance.GetType();  
  5.     FieldInfo field = type.GetField(fieldname, flag);  
  6.     return (T)field.GetValue(instance);  

2、得到私有属性的值:

  1. public static T GetPrivateProperty<T>(this object instance, string propertyname)  
  2. {  
  3.     BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;  
  4.     Type type = instance.GetType();  
  5.     PropertyInfo field = type.GetProperty(propertyname, flag);  
  6.     return (T)field.GetValue(instance, null);  

3、设置私有成员的值:

  1. public static void SetPrivateField(this objectinstance, stringfieldname, objectvalue)   
  2. {   
  3.     BindingFlagsflag = BindingFlags.Instance | BindingFlags.NonPublic;   
  4.     Typetype = instance.GetType();   
  5.     FieldInfofield = type.GetField(fieldname, flag);   
  6.     field.SetValue(instance, value);   
  7. }  

4、设置私有属性的值:

  1. public static void SetPrivateProperty(this objectinstance, stringpropertyname, objectvalue)   
  2. {   
  3.     BindingFlagsflag = BindingFlags.Instance | BindingFlags.NonPublic;   
  4.     Typetype = instance.GetType();   
  5.     PropertyInfofield = type.GetProperty(propertyname, flag);   
  6.     field.SetValue(instance, value, null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值