Observer

    public abstract class Observer : Publisher
    {
        System.Object m_obj;
        List<FieldInfo> m_observeFields = new List<FieldInfo>();
        List<PropertyInfo> m_observeProperties = new List<PropertyInfo>();
        List<object> m_fieldValues = new List<object>();
        List<object> m_propertyValues = new List<object>();


        public Observer(System.Object obj)
        {
            m_obj = obj;


            var fields = m_obj.GetType().GetFields();
            foreach (var f in fields)
            {
                object[] attributes = f.GetCustomAttributes(typeof(ObserveAttribute), false);
                if (attributes.Length > 0)
                {
                    m_observeFields.Add(f);
                    m_fieldValues.Add(f.GetValue(m_obj));
                }
            }
            var properties = m_obj.GetType().GetProperties();
            foreach (var p in properties)
            {
                if (!p.CanRead)
                    continue;
                object[] attributes = p.GetCustomAttributes(typeof(ObserveAttribute), false);
                if (attributes.Length > 0)
                {
                    m_observeProperties.Add(p);
                    m_propertyValues.Add(p.GetValue(m_obj, null));
                }
            }

        }

   public void Update()
        {
            for(int i = 0; i < m_observeFields.Count; i++)
            {
                var m = m_observeFields[i];
                object newValue = m.GetValue(m_obj);
                if (!object.Equals(newValue, m_fieldValues[i]))
                {
                    Notify("valueChanged", m_obj, m.Name);
                    //Debug.Log("valueChanged: " + m_obj.ToString() + " propName: " + m.Name);
                    m_fieldValues[i] = newValue;
                }
            }
            for (int i = 0; i < m_observeProperties.Count; i++)
            {
                var p = m_observeProperties[i];
                object newValue = p.GetValue(m_obj, null);
                if (!object.Equals(newValue, m_propertyValues[i]))
                {
                    Notify("valueChanged", m_obj, p.Name);
                    m_propertyValues[i] = newValue;
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值