如何为每个插入到字典 c# 定义行为?就像每次插入都写入日志

How to define a behavior for each insert to dictionary c#? like write to the log each insert

我有一个包含 Dictionary 字段的 class。 我想将每个插入记录到字典中。 最优雅的方法是什么?

我试着定义了一个属性的字典,并把日志放在了set方法中:

private Dictionary<string, string> _myDictionary = new Dictionary<string, string>();

private Dictionary<string, string> MyDictionary
{
    get
    {
        return _myDictionary;
    }
    set
    {
        _logger.Trace($"MyDictionary.set: value = {value}");

        _myDictionary = value;
    }
}

但这与插入无关,仅与字典引用的分配有关。 我想像以下操作一样“捕获”一组键值,并将其记录下来:

MyDictionary["key"] = "some value";

怎么做?

您可以创建一个派生自 Dictionary<TKey, TValue> 的 class 并替换标准的 Add 方法和索引器 属性 在调用基本实现之前添加某种日志记录

public class LoggedDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{

    public new void Add(TKey key, TValue value)
    {
        // Replace with whatever logging method you use
        Console.WriteLine($"Add called {key} = {value}");
        base.Add(key,value);
    }

    public new TValue this[TKey key]
    {
        get
        {
            // Replace with whatever logging method you use
            Console.WriteLine("Get called");
            return base[key];
        }
        set
        {
            // Replace with whatever logging method you use
            Console.WriteLine($"Set called {key} = {value}");
            base[key] = value;
        }
    }
}

void Main()
{
    LoggedDictionary<string, string> logged = new LoggedDictionary<string, string>();
    logged.Add("test", "t1");
    logged["test"] = "t2";
}

如果您的目的是记录每个更改字典的操作,那么您还需要重新定义 Remove 方法

public new bool Remove(TKey key)
{
    Console.WriteLine($"Remove called for {key}");
    return base.Remove(key);
}
public new bool Remove(TKey key, out TValue value)
{
    Console.WriteLine($"Remove called for {key}");
    return base.Remove(key, out value);
}