/// <summary>设置扩展属性</summary> /// <typeparam name="TDependEntity"></typeparam> /// <param name="key"></param> /// <param name="value"></param> protected virtual void SetExtend <TDependEntity>(String key, Object value) where TDependEntity : Entity <TDependEntity>, new() { // 针对每个类型,仅注册一个事件 Type type = typeof(TDependEntity); List <String> list = null; if (!Depends.TryGetValue(type, out list)) { list = new List <String>(); Depends.Add(type, list); } lock (Extends) { Extends[key] = value; if (!list.Contains(key)) { list.Add(key); } // 停止扩展属性的情况下不生效 if (!StopExtend && list.Count == 1) { Entity <TDependEntity> .Meta.OnDataChange += RemoveExtend; } } }
/// <summary>获取扩展属性,获取数据时向指定的依赖实体类注册数据更改事件</summary> /// <typeparam name="TDependEntity">依赖实体类,该实体类数据更改时清空所有依赖于实体类的扩展属性</typeparam> /// <typeparam name="TResult">返回类型</typeparam> /// <param name="key">键值</param> /// <param name="func">回调</param> /// <param name="cacheDefault">是否缓存默认值,可选参数,默认缓存</param> /// <returns></returns> protected virtual TResult GetExtend <TDependEntity, TResult>(String key, Func <String, Object> func, Boolean cacheDefault) where TDependEntity : Entity <TDependEntity>, new() { Object value = null; if (Extends.TryGetValue(key, out value)) { return((TResult)value); } if (StopExtend) { return(default(TResult)); } // 针对每个类型,仅注册一个事件 Type type = typeof(TDependEntity); List <String> list = null; if (!Depends.TryGetValue(type, out list)) { list = new List <String>(); Depends.Add(type, list); } // 这里使用了成员方法GetExtend<TDependEntity>而不是匿名函数,为了避免生成包装类,且每次调用前实例化包装类带来较大开销 return((TResult)Extends.GetItem <Func <String, Object>, List <String> >(key, func, list, new Func <String, Func <String, Object>, List <String>, Object>(GetExtend <TDependEntity>), cacheDefault)); }
/// <summary>清理依赖于某类型的缓存</summary> /// <param name="dependType">依赖类型</param> void RemoveExtend(Type dependType) { // 停止扩展属性的情况下不生效 if (StopExtend) { return; } if (Depends == null || Extends.Count < 1) { return; } // 找到依赖类型的扩展属性键值集合 //List<String> list = Depends[dependType]; List <String> list = null; if (!Depends.TryGetValue(dependType, out list) || list == null || list.Count < 1) { return; } lock (Extends) { // 清理该类型的所有扩展属性 foreach (String key in list) { //if (Extends.ContainsKey(key)) { //if (Database.Debug) //{ // Object value = Extends[key]; // Database.WriteLog("RemoveExtend({0}, {1}, {2})", key, this, value != null ? value.ToString() : "null"); //} Extends.Remove(key); } } list.Clear(); } }