【问题标题】:Subclass-specific static member data子类特定的静态成员数据
【发布时间】:2012-11-29 17:47:14
【问题描述】:

我正在尝试实现一个类族,这些类跟踪每个类中存在的实例数。因为所有这些类都有这种行为,所以我想把它拉到一个超类中,这样我就不必对每个类重复实现了。考虑以下代码:

class Base
{
    protected static int _instances=0;
    protected int _id;

    protected Base()
    {
        // I would really like to use the instances of this's class--not
        // specifically Base._instances
        this._id = Base._instances;
        Base._instances++;
    }
}

class Derived : Base
{
                                // Values below are desired,
                                // not actual:
    Derived d1 = new Derived(); // d1._id = 0
    Derived d2 = new Derived(); // d2._id = 1
    Derived d3 = new Derived(); // d3._id = 2

    public Derived() : base() { }
}

class OtherDerived : Base
{
                                            // Values below are desired,
                                            // not actual:
    OtherDerived od1 = new OtherDerived();  // od1._id = 0
    OtherDerived od2 = new OtherDerived();  // od2._id = 1
    OtherDerived od3 = new OtherDerived();  // od3._id = 2

    public OtherDerived() : base() { }
}

如何实现每个类的实例计数器(与基类的计数器分开的计数器)?我试过混合静态和抽象(不编译)。请指教。

【问题讨论】:

    标签: c# inheritance static


    【解决方案1】:

    不,你不能那样做。但是您可以拥有一个静态的Dictionary<Type, int>,并通过调用GetType 在执行时找出类型。

    class Base
    {
        private static readonly IDictionary<Type, int> instanceCounterMap
            = new Dictionary<Type, int>();
        protected int _id;
    
        protected Base()
        {
            // I don't normally like locking on other objects, but I trust
            // Dictionary not to lock on itself
            lock (instanceCounterMap)
            {
                // Ignore the return value - we'll get 0 if it's not already there
                instanceCounterMap.TryGetValue(GetType(), out _id);
                instanceCounterMap[GetType()] = _id + 1;    
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我建议不要试图让一个类来计算它自己的实例,而是创建一个工厂类来管理实例的生命周期。而不是新建一个“OtherDerived”,而是使用 Build 或 Create 方法实现 OtherDerivedFactory 来为它们提供服务。在内部,它可以对实例进行计数。

      哎呀,使用接口对其进行更多抽象,然后您可以在运行时注入工厂。非常适合测试、替代实现等。

      【讨论】:

      • 您能提供一些示例代码吗?我对工厂的概念非常熟悉。
      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      相关资源
      最近更新 更多