There is a base abstract class and 3 other classes that successively inherit the implementation of the previous one (BaseAbstract-> A-> B-> C). When creating a new instance of one of these three classes, a static field (counter) in the corresponding class is used to calculate the total number of instances of a particular class, the output of which is done through a static method.
abstract class BaseAbstract { public BaseAbstract() { //инициализация полей абстрактного класса IncStaticField(); //вызов абстрактного метода в конструкторе абстрактного класса } protected abstract void IncStaticField(); } class A : BaseAbstract { private static int instNo = 0; //стат. поле protected override void IncStaticField() { A.instNo = A.instNo + 1; //тип указываю здесь лишь для "пояснения" собственных намерений } public static string Info() //вывод кол-ва созданных экземпляров конкретного класса { return "Общее количество созданных экземпляров класса A: " + instNo; } } class B : A { private static int instNo = 0; protected override void IncStaticField() { B.instNo = B.instNo + 1; } public static new string Info() // замещение { return "Общее количество созданных экземпляров класса B: " + instNo; } } class C : B { //аналогичная реализация, как в классе B } This implementation successfully calculates the number of instances created for each class and displays their values through a call to the Info () method of a particular class.
1) How safe is the call to an abstract (virtual) method in the constructor, thanks to which the static field of a particular class is increased?
2) Is it possible to simplify the implementation of the IncStaticField () method so that it is not necessary to declare it in each class only to indicate the class of the static field that should be increased?