public class PropertySet<N, T> where N : struct ,IConvertible //基类
where T : IComparable
{
protected T[] mValues;
protected Action<T>[] mActions;
public PropertySet(N maxCount)
{
int count = ToIndex(maxCount);
mValues = new T[count];
mActions = new Action<T>[count];
}
public void AddChanageEvent(N key, Action<T> handler)
{
mActions[ToIndex(key)] += handler;
}
public void RemoveChangeEvent(N key, Action<T> handler)
{
mActions[ToIndex(key)] -= handler;
}
public virtual int ToIndex(N key)
{
return key.ToInt32(null); //12bytes GC Alloc
}
public virtual T this[N key]
{
get
{
return mValues[ToIndex(key)];
}
set
{
int index = ToIndex(key);
if (value.CompareTo(mValues[index]) != 0)
{
mValues[index] = value;
if (mActions[index] != null)
{
mActions[index](value);
}
}
}
}
}
public class PlayerPropertySet : PropertySet<EPlayerProperty, float>
{
public PlayerPropertySet() : base(EPlayerProperty.Max)
{
mCryptoValues = new FloatCryptoWrapper[(int)EPlayerProperty.Max];
for (int i = 0; i < mCryptoValues.Length; i++)
{
mCryptoValues[i] = new FloatCryptoWrapper(0.0f);
}
}
public override int ToIndex(EPlayerProperty key)
{
return (int)key;
}
public override float this[EPlayerProperty key]
{
get
{
return mCryptoValues[ToIndex(key)].Value;
}
set
{
int index = ToIndex(key);
if ((mCryptoValues[ToIndex(key)].Value) != value)
{
mCryptoValues[ToIndex(key)].Value = value;
if (mActions[index] != null)
{
mActions[index](value);//触发时间,括号为传递参数值
}
}
}
}
protected FloatCryptoWrapper[] mCryptoValues;
}
用法
//注册事件,并使用
PlayerPropertySet PropertySet;
Player.PropertySet.AddChanageEvent(EPlayerProperty.Health, OnHealthChange);
void OnHealthChange(float newValue)
{
//写处理逻辑
}
赋值、取值
float test = PropertySet[EPlayerProperty.Health];
PropertySet[EPlayerProperty.Health] = 1f;