码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-06-12 21:04:58      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:code   tar   ext   get   string   os   

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

例前段时间,在项目中客户提出了能对报表的列进行顺序调整,并且同一台机子上不同的账号登录修改后的保存能独立,这个好解决应用微软的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);
            }
          
        }

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

如何调用封装的私有方法或私有对象,布布扣,bubuko.com

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

标签:code   tar   ext   get   string   os   

原文地址:http://www.cnblogs.com/chujinlong/p/3781520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!