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 に答える