我正在尝试实现一个类系列,这些类跟踪每个类存在多少个实例。因为所有这些类都有这种行为,所以我想把它拉成一个超类,所以我不必重复每个类的实现。请考虑以下代码:
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() { }
}
如何实现每类实例计数器(一个与基类计数器分开的计数器)?我试过混合静电和放大器抽象(不编译)。请指教。
答案 0 :(得分: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;
}
}
}
答案 1 :(得分:0)
我建议不要试图让类来计算自身的实例,而是创建一个管理实例生命周期的工厂类。而不是新的&#39; OtherDerived&#39;您使用Build或Create方法实现OtherDerivedFactory以提供它们。在内部,它可以计算实例。
哎呀,用接口抽象一点,然后你可以在运行时注入工厂。非常适合测试,替代实施等。