限制等级最多3次. [英] Restriction of class for instatiate maximum 3 times.

查看:58
本文介绍了限制等级最多3次.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序只有一个类,我想将限制应用于对象创建.它只能在应用程序中实例化三个时间.

My Application has one class and i want to apply the restriction for objects creation. It can instantiate only three time in application.

推荐答案

private const int max = 3;
private static int counter = 0;
private static readonly object m_lock = new object();

public static MyClass CreateInstance()
{
    lock (m_lock)
    {
        return (++counter > max) ? null : new MyClass();
    }
}

private MyClass()
{

}




RS注意:为线程安全添加了锁定.




RS Note: Added lock for thread safety.


您可以使用 Singleton设计模式.
:)
You may use the Singleton design pattern.
:)


public class classname
{
   private static classname instance;
   private Singleton() {}
   public static classname Instance
   {
      get 
      {
         if (instance <= 3)
         {
            instance = new classname();
         }
         return instance;
      }
   }
}



Singleton创建单个实例,

我对此不确定,但这可能会有所帮助....



Singleton creates single instance,

I am not sure about this but, this may help....


这篇关于限制等级最多3次.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆