计数器没有设置回零C#

Rah*_*ulD -2 c# asp.net counter

我已经创建了一个单例类,当我在启动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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 5

每次附加调试器时IIS都不会重新启动AppPool,如果要重置计数器,则必须重建解决方案或触摸web.config文件以强制IIS重新启动AppPool(您的静态变量将保留到AppPool回收).

Singleton模式是一种确保整个应用程序中只有一个对象实例的方法,因此在类上设置私有构造函数并确保实例化实例的调用是线程安全的很重要.

以下是如何在C#中实现单例的两个示例:

public class Singleton
{
    private static readonly Singleton SingleInstance;

    static Singleton()
    {
        /* initializes the static field the first time anything is accessed on 
           the Singleton class .NET ensures threadsafety on static initializers. */
        SingleInstance = new Singleton(Datetime.Now);
    }

    public static Singleton Instance
    {
        get
        {
            return SingleInstance;
        }
    }
    /// <summary>
    /// Keep the constructure private on Singleton objects to avoid other instances being contructed
    /// </summary>
    private Singleton(DateTime value)
    {
        Value = value;
    }

    public DateTime Value { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是.NET 4或更高版本,您还可以使用Lazy来简化单例

public class Singleton
{
    private static readonly Lazy<Singleton> LazyInstance = new Lazy<Singleton>(() => new Singleton(DateTime.Now));

    public static Singleton Instance
    {
        get
        {
            return LazyInstance.Value;
        }
    }
    /// <summary>
    /// Keep the constructure private on Singleton objects to avoid other instances being contructed
    /// </summary>
    private Singleton(DateTime value)
    {
        Value = value;
    }

    public DateTime Value { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)