特定于子类的静态成员数据 [英] Subclass-specific static member data

查看:55
本文介绍了特定于子类的静态成员数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个类家族,这些类可以跟踪每个类中存在多少个实例.因为所有这些类都具有这种行为,所以我想将其拉入单个超类中,这样我就不必在每个类中重复执行.考虑以下代码:

I'm trying to implement a family of classes who keep track of how many instances exist on a per-class basis. Because all of these classes have this behavior, I'd like to pull it out into a single superclass so I don't have to repeat the implementation with each class. Consider the following code:

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

如何实现每个类的实例计数器(一个与基类的计数器分开的实例)?我已经尝试过将静态&抽象(不编译).请告知.

How can I achieve a per-class instance counter (one that is separate from the base class's counter)? I've tried mixing static & abstract (doesn't compile). Please advise.

推荐答案

不,您不能这样做.但是您可以使用静态的Dictionary<Type, int>,并在执行时通过调用GetType找出类型.

No, you can't do that. But you can have a static Dictionary<Type, int> and find out the type at execution time by calling 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;    
        }
    }
}

这篇关于特定于子类的静态成员数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆