gpt4 book ai didi

c# - 跟踪基类中的实例化

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:47 26 4
gpt4 key购买 nike

目前我以这种方式跟踪基类实例的数量:

private static int _instanceCount = 0;

protected BaseClass()
{
Interlocked.Increment(ref _instanceCount);

if (_instanceCount > 1)
throw new Exception("multiple instances detected.");
}

然后我有这样的构造函数的子类:

public ChildClass(): base()
{
// Empty Constructor
}

当然我也有异常(exception)。我可以将代码从 BaseClass 构造函数移动到 ChildClass 构造函数,但这是一种冗余(所有子级都具有相同的代码)。

有什么方法可以在BaseClass中实现吗?

获取异常是否意味着我真的尝试根据上述代码创建多个 ChildClass 实例?

最佳答案

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code ?

这意味着有超过 1 个基类(派生)实例。

Is there any way to do it it the BaseClass ?

在基类中做什么?这部分问题不清楚。您已经在基类中这样做了。


但是您的设置不会非常有用,因为它只允许基类的 1 个实例,因此也只允许派生类的 1 个实例。

我假设您希望每个派生类都是单例。要在基类中实现它,您需要一个静态 HashSet,您可以在其中使用 Typename (this.GetType().Name) 作为键。

关于c# - 跟踪基类中的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4767360/

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