是否有可能知道何时创建任何给定类型的新对象?

时间:2017-12-15 17:55:16

标签: c# types

有没有办法设置一种观察者来知道在我的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();
    }

0 个答案:

没有答案