如何调用封装的私有方法或私有对象

一般情况下,一个对象的私有方法或私有属性,是无法调用的,但在开发过程中,突然发现我们要钻牛角了,你不准调,但我一定要调

例前段时间,在项目中客户提出了能对报表的列进行顺序调整,并且同一台机子上不同的账号登录修改后的保存能独立,这个好解决应用微软的CacheManager能很好的解决,牛角来了。。。。如果我要在项目中删除所有关于某个报表的记忆缓存咋办,可是只有一个公共的Remove(String Key)方法;问题是Key我用的是用户账号,我不想循环系统所有的账号去删除。。。。。

在调试过程我发现CacheManager这个对象里面有一个私有对象“realCache”,包含了所有的Key对象,如是解决办法之一如下:

 System.Type type = cache.GetType();//cache为CacheManager对象

FieldInfo fi = type.GetField("realCache", BindingFlags.NonPublic | BindingFlags.Instance);//realCache 为封装的私有属性,

Microsoft.Practices.EnterpriseLibrary.Caching.Cache _cache = (Microsoft.Practices.EnterpriseLibrary.Caching.Cache)fi.GetValue(cache);//对象强制转换

System.Collections.Hashtable table = _cache.GetType().GetProperty("CurrentCacheState").GetValue(_cache, null) as System.Collections.Hashtable;//CurrentCacheState对象包含了我想要的

 System.Collections.IDictionaryEnumerator enumerator = table.GetEnumerator();
while (enumerator.MoveNext())
            {
                Microsoft.Practices.EnterpriseLibrary.Caching.CacheItem item = enumerator.Value as Microsoft.Practices.EnterpriseLibrary.Caching.CacheItem;
                if (item != null)
                {
                    SupcanTemplates templates = item.Value as SupcanTemplates;//这个SupcanTemplates是我缓存的对象
                 if (templates != null)
                    {
                        templates.RemoveTemplate(templateId);//templateId是我对应的报表ID
                 }
                }
            }

原理通了很简单,如下面这个是我要调用别人的一个私有方法:

 protected virtual void OnHotKey(object sender, KeyEventArgs e)
        {
            string funcName = Enum.GetName(typeof(Keys), e.KeyCode);
            Type thisType = this.GetType();
            MethodInfo func = thisType.GetMethod(funcName,BindingFlags.Instance| BindingFlags.IgnoreCase |
                BindingFlags.Static | BindingFlags.NonPublic);
            if (func != null)
            {
                object[] parameters=new  object[]{sender,e};
                func.Invoke(this, parameters);
            }
          
        }

这是我第一次发,希望能够帮助到大家,以后会有更多的分享

转载于:https://www.cnblogs.com/chujinlong/p/3781520.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值