6

面试官:实现一个带值变更通知能力的Dictionary

 3 years ago
source link: https://www.cnblogs.com/JulianHuang/p/15146425.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如题, 你知道字典KEY对应的Value什么时候被覆盖了吗?今天我们聊这个刚性需求。

前文提要:

数据获取组件维护了业务方所有(在用)的连接对象,DBA能在后台无侵入的切换备份库。

上文中:DBA在为某个配置字符串切换新的连接信息时,SDK利用ClearPool(DBConnection conn)清空与这个连接相关的连接池。

清空的时机: 维护在用连接的字典键值发生变更。

今天本文就来实现一个带值变更通知能力的字典。

关键字: 变更 通知 字典

using System;
using System.Collections.Generic;
using System.Text;
namespace DAL
{
    public class ValueChangedEventArgs<TK> : EventArgs
    {
        public TK Key { get; set; }
        public ValueChangedEventArgs(TK key)
        {
            Key = key;
        }
    }

    public class DictionaryWapper<TKey, TValue>
    {
        public object  objLock = new object();
       
        private Dictionary<TKey, TValue> _dict;
        public event EventHandler<ValueChangedEventArgs<TKey>> OnValueChanged;
        public DictionaryWapper(Dictionary<TKey, TValue> dict)
        {
            _dict = dict;
        }
        public TValue this[TKey Key]
        {
            get { return _dict[Key]; }
            set
            {
                lock(objLock)
                {
                    try
                    {
                        if (_dict.ContainsKey(Key) && _dict[Key] != null && !_dict[Key].Equals(value))
                        {
                            OnValueChanged(this, new ValueChangedEventArgs<TKey>(Key));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"检测值变更或者触发值变更事件,发生未知异常{ex}");
                    }
                    finally
                    {
                        _dict[Key] = value;
                    }
                }
            }
        }
    }
}
  1. 定义值变更事件OnValueChanged 和变更时传递的事件参数ValueChangedEventArgs<TKey>
  2. 如何定义值变更,也就是如何判定值类型、引用类型的相等性 #equalhashcode#
  3. DictionaryWapper的表征实现也得益于C#索引器特性
订阅值变更事件
var _dictionaryWapper = new DictionaryWapper<string, string>(new Dictionary<string, string> { });
_dictionaryWapper.OnValueChanged += new EventHandler<ValueChangedEventArgs<string>>(OnConfigUsedChanged);

//----

 public static void OnConfigUsedChanged(object sender, ValueChangedEventArgs<string> e)
{
   Console.WriteLine($"字典{e.Key}的值发生变更,请注意...");          
}

最后像正常Dictionary一样使用DictionaryWapper:

// ---
 _dictionaryWapper[$"{dbConfig}:{connectionConfig.Provider}"] = connection.ConnectionString;

OK,本文实现了一个 带值变更通知能力的字典,算是一个刚性需求。
温习了 C# event 索引器的用法。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK