我创建了一个单例类,当我在启动 Visual Studio 后第一次执行它时,它会打印预期的结果,因为 count 的值最初为零,当它达到一个时它会退出循环,但是,当我第二次执行它,计数器值仍然保持为 1,即使在我停止调试后它也不会归零。请帮助我找到问题的解决方案。谢谢。我的班级代码如下:
public partial class Singleton_class : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CEO c1 = CEO.GetCeoObject("Rahul", "MS", 28);
CEO c2 = CEO.GetCeoObject("Ram", "MS", 26);
Response.Write(c1.name + " " + c1.qualifiaction + " " + c1.age + "<br/>");
Response.Write(c2.name + " " + c2.qualifiaction + " " + c2.age + "<br/>");
}
}
namespace Singleton
{
public class CEO
{
public static CEO c1;
public static int count;
public string name;
public string qualifiaction;
public int age;
private CEO(string n, string q, int a)
{
this.name = n;
this.qualifiaction = q;
this.age = a;
}
public static CEO GetCeoObject(string name, string quali, int age)
{
if (count == 0) //this remains at one
{
c1 = new CEO(name, quali, age);
count++;
}
return c1;
}
}
}