有没有办法设置一种观察者来知道在我的app域中是否创建了给定X类型的新对象,我的意思是检测何时实例化类。
想要做的事情(在粉红色的世界中)如下所示:
public class BlackBoxObserver<T> where T : class
{
public event Action SomewhereBeyondYourSightAInstanceHasBeenCreated;
public void StartTracking()
{
//todo black magic...
}
protected virtual void OnSomewhereBeyondYourSightAInstanceHasBeenCreated()
=> SomewhereBeyondYourSightAInstanceHasBeenCreated?.Invoke();
}
然后使用它:
private static void Main()
{
var dictionaryObserver = new BlackBoxObserver<Dictionary<string,string>>();
dictionaryObserver.StartTracking();
dictionaryObserver.SomewhereBeyondYourSightAInstanceHasBeenCreated +=
() => Console.WriteLine("Dictionary created somewhere!");
Console.ReadLine();
}