zoukankan      html  css  js  c++  java
  • 巧用泛型和Lambda解决只读对象的缓存技巧

        /// <summary>
        
    /// 只读缓存辅助
        
    /// </summary>
        
    /// <typeparam name="KeyType">键类型</typeparam>
        
    /// <typeparam name="ValueType">值类型</typeparam>
        public static class Cache<KeyType, ValueType>
        {
            
    public delegate ValueType GetValue(KeyType key);
            
    private static Dictionary<KeyType, ValueType> data=new Dictionary<KeyType,ValueType>();

            
    /// <summary>
            
    /// 获取缓存中的数据
            
    /// </summary>
            
    /// <param name="key"></param>
            
    /// <param name="get">Lambda表达式,当缓存不存在时获取值的委托</param>
            
    /// <returns></returns>
            public static ValueType Get(KeyType key, GetValue get)
            {
                
    if (data.ContainsKey(key))
                    
    return data[key];
                
    else
                {
                    ValueType value 
    = get(key);
                    data.Add(key,value);
                    
    return value;
                }
            }
        }

    使用例子:

    反射MyModel对象所有属性并且缓存

     PropertyInfo[] MyProperty = Cache<Type, PropertyInfo[]>.Get(typeof(MyModel), p => p.GetProperties());

  • 相关阅读:
    iStylePDF c#集成开发示例
    纯js 实现 HTML 元素拖拽,
    前端自动滚动
    双向选择排序(暂定)
    uniapp 分享链接
    Could not find a declaration file for module 'vue-xxx'.
    精通JavaScript(重点内容笔记)更新中...
    如何让DIV模块随着页面固定和不固定
    序列不包含任何匹配元素
    PHPStorm配置Apache服务器(wampServer 版)
  • 原文地址:https://www.cnblogs.com/passer/p/1375687.html
Copyright © 2011-2022 走看看