为什么单例类中的实例成员是静态的?
这是一个单例类,
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
我的问题是static Singleton instance=null;
为什么这是静态的?
This is a singleton class
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
my question is static Singleton instance=null;
why this is static?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
“实例”字段保存唯一实例的引用。
它存储在静态变量中,因为它的范围必须是类本身而不是特定实例。
The 'instance' field holds the reference of the one and only instance.
It is stored in a static variable because its scope has to be the class itself and not a particular instance.
因为您在静态属性(实例)中引用变量,并且不能在静态方法或属性中引用实例变量。
拥有单例的想法是始终只有一个实例在运行。
Because you are referencing the variable inside a static Property (Instance) and you can't reference instance variables inside static methods or properties.
The idea of having a Singleton is to only have one and only one instance at all times running.
Singleton 的目的是只拥有该对象的一个实例[1]。通过使用私有静态实例创建一个密封类,该实例在第一次访问时自动实例化,您可以提供其必要的特征,即仅创建实际对象的一个副本,然后由系统中其他地方的 Singleton.Instance 属性访问该副本。
[1] 无论如何,在任何 AppDomain 内。
The purpose of Singleton is to have only one instance of that object[1]. By making a sealed class with a private static instance which is automatically instantiated on first access, you provide its necessary trait of only creating one copy of the actual object that is then accessed by the Singleton.Instance property elsewhere in the system.
[1] within any AppDomain, anyway.
因为您只需要程序中存在一个(静态)实例
Because you only want one (static) instance ever in the program
它是静态的,因此 Singleton 类型的每个实例都将使用相同的变量,因此是“单例”模式。
It is static so every instance of the Singleton type will use the same variable, hence the "singleton" pattern.
简而言之,单例是一种设计模式,用于确保在给定范围内只创建某个事物的一个实例。
这种模式是通过几个主要概念来实现的:
object
您提供的示例代码是单例模式的教科书示例。
Succinctly, Singleton is a design pattern used to ensure that only one instance of something is ever created within a given scope.
This pattern is accomplished by a few main concepts:
object
The example code you provided is a textbook example of the Singleton pattern.
因为它不是静态的,所以它只是名义上的单例。我可以创建数千个它的实例。
Because it if would not be static, it would be a singleton only in name. And i could create thousands of instance of it.
我认为因为您使用了:
该函数是静态的,所以您的实例变量也需要是静态的。
I think because you used:
That function is static, so your instance variable need to be static too.