web*_*rc2 0 c# inheritance static
我正在尝试实现一个类系列,这些类跟踪每个类存在多少个实例.因为所有这些类都有这种行为,所以我想把它拉成一个超类,所以我不必重复每个类的实现.请考虑以下代码:
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() { }
}
Run Code Online (Sandbox Code Playgroud)
如何实现每类实例计数器(一个与基类计数器分开的计数器)?我试过混合静态和抽象(不编译).请指教.
不,你做不到.但是你可以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;
}
}
}
Run Code Online (Sandbox Code Playgroud)