count class instances for every derived class

前端 未结 7 2095
栀梦
栀梦 2021-02-19 09:09

is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?

Imagine I\'ve got access to the root class (e.g. object), an

相关标签:
7条回答
  • 2021-02-19 09:48

    Way in C# that sprung in my mind imediately:

    class A : IDisposable
    {
        static Dictionary<Type, int> _typeCounts = new Dictionary<Type, int>();
        private bool _disposed = false;
    
        public static int GetCount<T>() where T:A
        {
            if (!_typeCounts.ContainsKey(typeof(T))) return 0;
    
            return _typeCounts[typeof(T)];
        }
    
        public A()
        {
            Increment();
        }
    
        private void Increment()
        {
            var type = this.GetType();
            if (!_typeCounts.ContainsKey(type)) _typeCounts[type] = 0;
            _typeCounts[type]++;
        }
    
        private void Decrement()
        {
            var type = this.GetType();
            _typeCounts[type]--;            
        }
    
        ~A()
        {
            if (!_disposed) Decrement();
        }
    
        public void Dispose()
        {
            _disposed = true;
            Decrement();
        }
    }
    
    class B : A
    {
    
    }
    

    And how to use it:

            A a1 = new A();
            Console.WriteLine(A.GetCount<A>());
            A a2 = new A();
            Console.WriteLine(A.GetCount<A>());            
    
            using(B b1 = new B())
            {
                Console.WriteLine(B.GetCount<B>());
            }
            Console.WriteLine(B.GetCount<B>());
    

    The output could be done differently maybe. And its not pure OOP, but nor are C++ or Java examples in this thread. But it doesnt require a bit of code in inheriting class.

    And dont forget about correcly disposing your objects!!

    0 讨论(0)
提交回复
热议问题