菲佣WPF——3(关于NotifyObject重大bug修复)
之前的NotifyObjec有问题。是多个属性同时对一个Object进行操作。
新代码如下。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Linq.Expressions; namespace WpfApplication4 { public abstract class NotifyObject:INotifyPropertyChanged { #region << Field >> private Dictionary<string, object> cache = new Dictionary<string, object>(); #endregion #region << Property >> public event PropertyChangedEventHandler PropertyChanged; #endregion #region << Method >> public T GET<T>(Expression<Func<T>> express) { return GetPropertyValue<T>(GetPropertyName<T>(express)); } public void SET<T>(Expression<Func<T>> express, object obj) { SetPropertyValue(GetPropertyName<T>(express), obj); } private string GetPropertyName<T>(Expression<Func<T>> express) { var memExpress = (MemberExpression)express.Body; if (memExpress == null) throw new Exception("The expression is valid"); return memExpress.Member.Name; } private T GetPropertyValue<T>(string propertyName) { if (string.IsNullOrEmpty(propertyName)) return default(T); else { if (cache.ContainsKey(propertyName)) return (T)cache[propertyName]; else return default(T); } } private void SetPropertyValue(string propertyName, object obj) { if (cache.ContainsKey(propertyName)) { if (!Object.ReferenceEquals(cache[propertyName], obj)) { cache[propertyName] = obj; Notify(propertyName); } } else { cache.Add(propertyName, obj); Notify(propertyName); } } private void Notify(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }