using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace IFramework
{
///
/// 可观测 Object
///
public abstract class ObservableObject : Unit
{
private Dictionary _callmap;
///
/// Ctor
///
protected ObservableObject()
{
_callmap = new Dictionary();
}
///
/// 注册数值变化监听
///
///
///
public void Subscribe(string propertyName, Action listener)
{
if (!_callmap.ContainsKey(propertyName))
_callmap.Add(propertyName, null);
_callmap[propertyName] += listener;
}
///
/// 取消注册数值变化监听
///
///
///
public void UnSubscribe(string propertyName, Action listener)
{
if (!_callmap.ContainsKey(propertyName))
throw new Exception($"Have not Subscribe {propertyName}");
_callmap[propertyName] -= listener;
if (_callmap[propertyName] == null)
_callmap.Remove(propertyName);
}
///
/// 获取属性
///
///
/// 获取的属性
/// 属性名称
///
protected T GetProperty(ref T property, [CallerMemberName]string propertyName = "")
{
if (ObservableObjectHandler.handler != null)
{
//if (string.IsNullOrEmpty(propertyName))
// propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name);
ObservableObjectHandler.handler.Subscribe(this, propertyName);
}
return property;
}
///
/// 设置属性
///
///
/// 赋值的变量
/// 变化的值
/// 属性名称
protected void SetProperty(ref T property, T value, [CallerMemberName]string propertyName = "")
{
if (EqualityComparer.Default.Equals(property, value)) return;
//if (string.IsNullOrEmpty(propertyName))
// propertyName = GetProperyName(new StackTrace(true).GetFrame(1).GetMethod().Name);
property = value;
PublishPropertyChange(propertyName);
}
///
/// 发布属性发生变化
///
/// 属性名称
protected void PublishPropertyChange(string propertyName)
{
if (!_callmap.ContainsKey(propertyName)) return;
if (_callmap[propertyName] == null) return;
_callmap[propertyName].Invoke();
}
///
/// 释放时
///
protected override void OnDispose()
{
_callmap.Clear();
_callmap = null;
}
//private string GetProperyName(string methodName)
//{
// if (methodName.StartsWith("get_") || methodName.StartsWith("set_") ||
// methodName.StartsWith("put_"))
// {
// return methodName.Substring("get_".Length);
// }
// throw new Exception(methodName + " not a method of Property");
//}
}
}