注意:这是家庭作业。
我有两个类,一个继承自另一个。赋值告诉我们使类能够跟踪每个类创建的实例总量。
class FirstClass
{
private static int _instancesCreated = 0;
public FirstClass()
{
_instancesCreated++;
}
}
据我所知,这段代码效果很好。问题是我有一个子类,必须调用它的父类的构造函数。
class SecondClass:FirstClass
{
public SecondClass() : base()
{
}
}
所以现在问题就变成了如何正确地将两者分开。由于我必须调用父构造函数,该类的_instancesCreated将变得不正确,尽管我认为它在某种意义上是真的......?
感谢您的帮助
答案 0 :(得分:4)
最简单的方法是保护_instancesCreated,然后在每个子类构造函数中减少它。这就是你如何使_instancesCreated只存储基类实例的数量。对于计算子类实例,您应该为每个实例添加静态字段,并在构造函数中增加它们,就像在基类中一样。
答案 1 :(得分:0)
class SecondClass:FirstClass
{
private static int _sub_instancesCreated = 0;
public SecondClass() : base()
{
_sub_instancesCreated ++;
}
}
class FirstClass
{
private static int _instancesCreated = 0;
public FirstClass()
{
_instancesCreated++;
}
protected FirstClass(int i)
{
}
}
class SecondClass:FirstClass
{
private static int _sub_instancesCreated = 0;
public SecondClass() : base(2) //dummy
{
_sub_instancesCreated ++;
}
}
答案 2 :(得分:0)
更通用的解决方案(如果有点矫枉过正):
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new BaseClass();
new BaseClass();
new DerivedClass();
Console.WriteLine("Base classes: {0}, Derived classes: {1}",
BaseClass.CountInstances<BaseClass>(),
BaseClass.CountInstances<DerivedClass>());
}
}
public class BaseClass
{
public static Dictionary<Type, int> InstanceCount =
new Dictionary<Type, int>();
public static int CountInstances<T>() where T : BaseClass
{
return BaseClass.InstanceCount.ContainsKey(typeof(T)) ? BaseClass.InstanceCount[typeof(T)] : 0;
}
public BaseClass()
{
if (!InstanceCount.ContainsKey(this.GetType()))
{
InstanceCount[this.GetType()] = 0;
}
InstanceCount[this.GetType()]++;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
: base()
{
}
}
}