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

来源:互联网 发布:中科大网络通 编辑:程序博客网 时间:2024/05/17 07:40

 

 

 

现象描述:

我有一个 缓存使用类,其有一个方法,从缓存中获取一个 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参数使用时需要注意的问题》

 

原创粉丝点击