c# - 限制类实例化
问题描述
在 C# 中,有没有办法停止实例化类,比如在 'n' 实例化之后?这个链接没有多大帮助。
关于尝试事情,我正在考虑使类成为静态的,但是在停止实例化之前必须实现'n'实例化。是否可以通过反射?
解决方案
您可能有一个私有静态计数器,在构造函数中将其递增并在达到限制时抛出异常。但请注意,这是一个非常奇怪且很可能是糟糕的设计。更好的方法是工厂模式
class LimitedInstantiation
{
private static int instCounter = 0;
public LimitedInstantiation()
{
instCounter++;
// limit your number of instances
if (instCounter > 3)
{
throw new Exception("Limit of instances reached");
}
}
~LimitedInstantiation()
{
// Reduce your number of instances in the destructor
instCounter--;
}
}
你可以这样测试:
try
{
var instance1 = new LimitedInstantiation();
var instance2 = new LimitedInstantiation();
var instance3 = new LimitedInstantiation();
// this should fail.
var instance4 = new LimitedInstantiation();
}
catch (Exception e)
{
Console.WriteLine(e);
}
推荐阅读
- google-cloud-dataflow - CDAP DataFusion GET 管道运行无效 IAP 凭证错误
- spring - 基于 Java 的 ETL 应用程序
- perl - Perl - 匹配文件中的开始/结束字符串
- python - 字典推导中 for 循环的 in 关键字如何工作?
- django - Django 3.0.7 版,/cart/ 'cart' 处的 TemplateSyntaxError 不是已注册的标签库
- python - 使用 python 龟的乒乓球游戏不工作
- python - 如何获得布尔numpy掩码的左下角和右下角
- ms-word - 如何从单词表中检索到数组?
- r - 如何比较两个 data.frames 并删除 R 中特定两列中的相同条目?
- node.js - Discord.js 应用系统?