首页 > 解决方案 > 限制类实例化

问题描述

在 C# 中,有没有办法停止实例化类,比如在 'n' 实例化之后?这个链接没有多大帮助。

关于尝试事情,我正在考虑使类成为静态的,但是在停止实例化之前必须实现'n'实例化。是否可以通过反射?

标签: c#instantiationencapsulation

解决方案


您可能有一个私有静态计数器,在构造函数中将其递增并在达到限制时抛出异常。但请注意,这是一个非常奇怪且很可能是糟糕的设计。更好的方法是工厂模式

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);
}

推荐阅读