【问题标题】:How to define a behavior for each insert to dictionary c#? like write to the log each insert如何为每个插入字典c#定义一个行为?就像每次插入都写入日志
【发布时间】:2022-01-17 05:58:47
【问题描述】:

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

我尝试定义字典的属性,并将日志放在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";

怎么做?

【问题讨论】:

  • 为什么不创建一个使用支持字典并公开各种操作方法的类?您可以执行任何需要的清理/记录,并且意图清晰明了。
  • 我想也许有一种通用的方法可以做到这一点,或者语言中的特定语法,如索引器或类似的东西,而不需要编写包装器。谢谢!

标签: c# dictionary logging indexing properties


【解决方案1】:

您可以创建一个派生自 Dictionary&lt;TKey, TValue&gt; 的类,并替换标准的 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2014-06-17
    • 2014-09-29
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多