我正在寻找一种确定程序中创建的结构对象数量的方法。这是出于教育目的。
我在SO上找到了这个答案,它适用于https://stackoverflow.com/a/12276687/363224类。因此,我尝试使用struct
做类似的事情,但正如预期的那样,它不会那样工作。
public struct Car
{
public string brand;
public static int ObjectsConstructed { get; private set; }
public Car(string brand)
{
this.brand = brand;
ObjectsConstructed++;
}
}
...
Car car1 = new Car("VW");
Car car2 = car1; // How can we increment the ObjectsConstructed?
List<Car> carList = new List<Car>();
carList.Add(car1); // How can we increment the ObjectsConstructed?
不调用Car(string)
构造函数,因为struct对象的副本称为某种memcpy,并且不会通过构造函数。结构也不允许显式的无参数构造函数。
如何使某种可以处理的复制构造函数?还是有另一种方法可以通过反射将这些信息从运行时中删除?
编辑
我写了一个测试,表明我的意思:
// This test passes, firstCar and sameCar are not the same.
[TestMethod]
public void HowManyTimesIsACarCreated()
{
Car firstCar = new Car();
Car sameCar = firstCar;
sameCar.brand = "Opel";
// It seems that you can change sameCar without changing firstCar
Assert.AreNotEqual(firstCar.brand, sameCar.brand);
// This one is tricky, because firstCar and sameCar are passed as parameters, so new objects would again be created as I would see it.
Assert.IsFalse(ReferenceEquals(firstCar, sameCar));
}
firstCar和sameCar不指向同一对象,因为如果sameCar我可以更改品牌,但是firstCar仍然相同。