我有一個包含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";
如何?
uj5u.com熱心網友回復:
您可以創建一個派生自Dictionary<TKey, TValue>并替換標準 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386407.html
