gpt4 book ai didi

c# - 父类和子类的实例计数

转载 作者:太空狗 更新时间:2023-10-30 01:25:58 26 4
gpt4 key购买 nike

我有一个父类型,并且有一些子类型继承自它。

我想确保父类和所有子类只有一个实例。父类型:

private static int _instanceCount = 0;

public ParentClass()
{
protected ParentClass() // constructor
{
_instanceCount++;

if (_instanceCount > 1)
throw new exception("Only one instance is allowed.");
}
}

示例子类:

private static int _instanceCount = 0;

public ChildClass() : ParentClass
{
public ChildClass() : base() // constructor
{
_instanceCount++;

if (_instanceCount > 1)
throw new exception("Only one instance is allowed.");
}
}

该解决方案适用于子类型,但是当它们调用基类构造函数时,我无法区分是否从其他类型调用了基构造函数,因此该解决方案失败了。

我怎样才能做到这一点?

最佳答案

你应该能够判断你是否被这样的子类调用:

if( this.GetType().Equals(typeof(ParentClass)) )
{
//we know we're not being called by a sub-class.
}

当然,您可以跳过在子类中递增计数的步骤,而只在父类中也这样做......并且存在线程问题。

关于c# - 父类和子类的实例计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com