静态变量如何保留递增的值 [英] How static variable can retain incremented value
问题描述
我在类中创建了一个静态变量并在构造函数中递增,认为无论何时我向类创建实例,静态变量都将重置为0.令我惊讶的是,第一次创建对象时对于类,静态变量(Counter)递增为1.第二次将对象创建到类时,静态变量保留递增的值(1)。这是静态的行为吗?
我尝试过:
I created a static variable in a class and incrementing in the constructor, thinking that whenever I created an instance to the class, the static variable will be reset to 0. To my utter surprise, the first time when I created the object to the class, static variable(Counter) is incremented to 1. The second time when I created the object to the class, the static variable is retaining the incremented value(1). Is this the behavior of static?
What I have tried:
class Singleton
{
private static int counter = 0;
Public Singleton()
{
counter++;
Console.WriteLine("Counter-" + counter);
}
}
static void Main(string[] args)
{
Singleton objSingleton = Singleton.getInstanse;
objSingleton.getMessage("Hi This is my first message!");
Singleton objSingleton2 = Singleton.getInstanse;
objSingleton.getMessage("Hi This is my second message!");
}
推荐答案
这不是你的代码:我可以说出两个原因。
1)它不会编译 - C#区分大小写,Public
与public $ c $不同c>
2)您显示的Singleton
类不包含getInstanse
方法,这对你的问题至关重要。
单例类的整个想法是系统中只有一个类的实例 - 所以构造函数始终声明为private
,而不是public
,因此它只能在类本身内创建。通常情况下,这将在GetInstance
方法或类似方法中,但实例将保留在私有静态
变量中。 class:
That isn't your code: I can tell for two reasons.
1) It won't compile - C# is case sensitive, andPublic
is not the same aspublic
2) YourSingleton
class as shown doesn't contain agetInstanse
method, which is crucial to your problem.
The whole idea of a singleton class is that there is one and only one instance of the class in the system - so the constructor is always declared asprivate
, notpublic
so it can only be created inside the class itself. Normally that would be in aGetInstance
method or similar, but the instance would be retained in aprivate static
variable inside the class:
class Singleton
{
private static int counter = 0;
private static Singleton instance = null;
private Singleton()
{
counter++;
Console.WriteLine("Counter-" + counter);
}
public void getMessage(string s)
{
Console.WriteLine(s);
}
public static Singleton GetInstance()
{
if (instance == null) instance = new Singleton();
return instance;
}
}
class Program
{
static void Main(string[] args)
{
Singleton objSingleton = Singleton.GetInstance();
objSingleton.getMessage("Hi This is my first message!");
Singleton objSingleton2 = Singleton.GetInstance();
objSingleton.getMessage("Hi This is my second message!");
Console.ReadLine();
}
}
这就是为什么你只得到1的计数器:只创建一个实例。
And that's why you only ever get a counter of 1: only one instance is ever created.
这篇关于静态变量如何保留递增的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!