计数器没有设置回零C#

时间:2013-06-19 22:42:19

标签: 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;
        }
    }
}

2 个答案:

答案 0 :(得分: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; }
}

如果您使用的是.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; }
}

答案 1 :(得分:4)

GetCeoObject在第一次调用时创建内部静态对象c1 当您再次调用它时,GetCeoObject将返回第一次调用中创建的c1 您将它分配给另一个变量,但这与第一个变量分配的c1实例的引用相同。它是对同一存储区的引用 当您打印值时,打印相同的值就不足为奇了。