日期:2014-05-18  浏览次数:21050 次

c# 自定义 泛型集合Dictionary中 TValue值被改变的事件
如题,如何自定义集合Dictionary<TKey,TValue>中的 TValue值被改变的事件,

C# code

class CommandText
    {
        public ArrayList text { get; set; }
        public Dictionary<string, string> textParams
        {
            get 
            {
                return value;
            }
            set
            {
                if (textParams != value)
                {
                    Host();
                    OnAssign();
                }
            }
        }

        private delegate void textParamsEventHandler();
        private event textParamsEventHandler Assign;
        public void OnAssign()
        {
            if (this.Assign != null)
            {
                Assign();
            }
        }
        //注册事件
        public void Host()
        {
            Assign += new textParamsEventHandler(StructText);
        }
        protected void StructText()
        {
            foreach (KeyValuePair<string, string> textParam in textParams)
            {
                //根据ROS命令规则,过滤第一条
                for (int i = 1; i < text.Count; i++)
                {
                    //判断commandText是否存在该 参数
                    int index = text[i].ToString().IndexOf(textParam.Key);
                    if (index >= 0)
                    {
                        //获取旧值
                        string old = text[i].ToString().Substring(index + 1, text[i].ToString().Length - index - 1);
                        //替换新值
                        text[i].ToString().Replace(old, textParam.Value);
                    }
                }
            }
        }


    }


请给出描述代码,不胜感激!给出 实例DEMO的,追加分数!

------解决方案--------------------
C# code
class DictionaryWapper<TKey, TValue>
{
    public class ValueChangedEventArgs<T> : EventArgs
    {
        public T Key { get; set; }
        public ValueChangedEventArgs(T key)
        {
            Key = key;
        }
    }
    private Dictionary<TKey, TValue> _dict;
    public event EventHandler OnValueChanged;
    public DictionaryWapper(Dictionary<TKey, TValue> dict)
    {
        _dict = dict;
    }
    public TValue this[TKey Key]
    {
        get { return _dict[Key]; }
        set 
        { 
            if (!_dict[Key].Equals(value)) 
            {
                _dict[Key] = value;
                OnValueChanged(this, new ValueChangedEventArgs<TKey>(Key));
            }
        }
    }
}