【问题标题】:Instance count on parent and children classes父类和子类的实例计数
【发布时间】:2011-08-21 21:19:50
【问题描述】:

我有一个父类型,并且有一些子类型继承自它。

我想确保只有一个父实例以及所有子类型。父类型:

private static int _instanceCount = 0;

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

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

示例子类:

private static int _instanceCount = 0;

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

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

该解决方案适用于子类型,但是当它们调用基类构造函数时,我无法区分是否从其他类型调用了基构造函数,因此解决方案失败。

我怎样才能做到这一点?

【问题讨论】:

  • 你可以通过单例类实现同样的功能
  • 单例在这里不起作用。我将这些类型与MEF 一起使用,它将根据需要延迟实例化它们。事实上,我已经将container 实现为更高级别的Singleton,这是为了确保我没有多个container

标签: c# inheritance instance


【解决方案1】:

听起来您想要Singleton 的功能。

【讨论】:

    【解决方案2】:

    好的...这可能是一个非常糟糕的hack...但是您可以从 Environment.StackTrace 获取堆栈跟踪,并在运行构造函数代码之前查看被调用者是否是您的子类。 大声笑...祝你好运! :)

    【讨论】:

      【解决方案3】:

      你应该能够判断你是否被这样的子类调用:

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

      当然,您可以跳过在子类中增加计数的步骤,并且只在父类中执行此操作......并且存在线程问题。

      【讨论】:

        【解决方案4】:

        可能还有其他方法可以解决您正在尝试做的事情,例如使用单例,但确保调用基本构造函数不会给您误报的一种方法是检查其类型,例如:

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

        【讨论】:

          猜你喜欢
          • 2013-06-10
          • 1970-01-01
          • 2021-08-28
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多