您的位置:首页 > 职场人生

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

2021-08-16 10:15 921 查看

如题, 你知道字典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. 如何定义值变更,也就是如何判定值类型、引用类型的相等性 #
    equal
    hashcode
    #
  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 索引器的用法。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐