开发者

Instance count on parent and children classes

开发者 https://www.devze.com 2023-03-04 13:14 出处:网络
I have a parent type and there are some children types inheriting from it. I want to make sure there is only开发者_StackOverflow社区 one instance of the parent and also for all the children types. Pa

I have a parent type and there are some children types inheriting from it.

I want to make sure there is only开发者_StackOverflow社区 one instance of the parent and also for all the children types. Parent type:

private static int _instanceCount = 0;

public ParentClass()
{
    protected ParentClass() // constructor
    {
        _instanceCount++;

    if (_instanceCount > 1)
        throw new exception("Only one instance is allowed.");
    }
}

Sample child class:

private static int _instanceCount = 0;

public ChildClass() : ParentClass
{
    public ChildClass() : base() // constructor
    {
        _instanceCount++;

        if (_instanceCount > 1)
            throw new exception("Only one instance is allowed.");
    }
}

The solution works for children types but when they call the base class constructor I cannot distinguish if the base constructor is called from other types or not so the solution fails.

How can I achieve this?


You should be able to tell if you're being called from a subclass like this:

if( this.GetType().Equals(typeof(ParentClass)) )
{
    //we know we're not being called by a sub-class.
}

Of course, you could just skip the step of incrementing the count in child classes and only do it in the parent as well...and there are threading issues.


It sounds like you want the functionality of a Singleton.


There are probably other ways to approach what you are trying to do, such as using Singletons, but one way to make sure that calling the base constructor doesn't give you a false positive would be to check its type, such as:

protected ParentClass()
{
  if (!GetType().Equal(typeof(ParentClass)))
  {
    // The child class has taken care of the check aleady
    return;
  }
}


ok... this may be a very bad hack... but you can get the stack trace from Environment.StackTrace and see if the callee was your child class just before your constructor code was run. lol... good luck! :)

0

精彩评论

暂无评论...
验证码 换一张
取 消