0

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

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() { }
}

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

4

2 回答 2

6

不,你不能那样做。但是你可以有一个静态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;    
        }
    }
}
于 2012-11-29T17:50:41.633 回答
0

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

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

于 2012-11-29T17:49:16.770 回答