سؤال

Currently I trace number of instances of a base class this way:

private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}

Then I have child classes with constructor like this:

public ChildClass(): base()
{
    // Empty Constructor
}

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?

هل كانت مفيدة؟

المحلول

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code ?

It means there is more than 1 baseclass(-derived) instance.

Is there any way to do it it the BaseClass ?

Do what in the baseclass? This part of the Questions is unclear. You're already doing it in the baseclass.


But your setup won't be very usefull as it will only allow 1 instance of the baseclass and hence of only 1 of the derived classes.

I'll assume you want each derived class to be a Singleton. To implement that in the base class you'll need for instance a static HashSet where you can use the Typename (this.GetType().Name) as key.

نصائح أخرى

If you want a Singleton factory, you could consider using an IoC container instead of rolling your own. Many IoC containers support Singleton factory behaviour as a standard feature. For instance you could use Unity.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top