一个 缓存并使用Out 参数的 有趣现象

 

 

 

现象描述:

我有一个 缓存使用类,其有一个方法,从缓存中获取一个 Dictionary<string, object> 对象, 用out 的方式,将其传出 为对象B

 

但有趣的 是 当B里有Add(key,value)的行为后,缓存中的Dictionary<string, object> 对象 也会有相应的键值对

              同时 当 B里有Clear()的行为后 ,缓存中的Dictionary<string, object> 对象也变成了Null。

  相关代码如下:

应用层 修改对象B  如   //tempdic.Clear();

  private Dictionary<string, object> tempdic = new Dictionary<string, object>();

 

 public List<Subject> GetAllSubject()
        {

            //tempdic.Clear();
            bool IfGot = this.TryGetCache(out tempdic);
           if (IfGot)
           {
            return (List<Subject>)(tempdic["subject"]);
           }
            return null;
        }

 

 

关于 this.TryGetCache(out tempdic);
的详细信息

  public static bool TryGetCache<T>(string CacheKey,out T t)
           {
            try
            {
                System.Web.Caching.Cache objCache = HttpRuntime.Cache;
                if (objCache[CacheKey] ==null)
                {
                    t = default(T);
                    return false;
                }
                else
                {
                    t = (T)objCache[CacheKey];
                    return true;
                }
            }
            catch 
            {
            throw new Exception("用指定类型转换缓存对象出现错误!");
             }
        }

 

代码说明 : 如上所示 TryGetCache<T>(string CacheKey,out T t)
 就是将  HttpRuntime.Cache里的值 传出到 tempdic ,但tempdic 得变化,同步到了  HttpRuntime.Cache里的值;这就是本文想描述的现象。以此为戒,以后使用 out方式时 要注意。(因为最开始在应用层只要一调用tempdic.Clear(),缓存就没有了,但始终查不出来原因,折腾几个来回,才明白是out的缘故;)

 

原因分析的过程 参见《c#中ref和out参数使用时需要注意的问题》

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值