gpt4 book ai didi

c# - C# 问题中的单例模式

转载 作者:太空宇宙 更新时间:2023-11-03 17:12:42 27 4
gpt4 key购买 nike

我正在研究 C# 的单例模式,我从 msdn 网站上找到了这个例子。

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();

private Singleton(){}

public static Singleton Instance
{
get
{
return instance;
}
}
}

Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton.

我不太确定内存什么时候会分配给

private static readonly Singleton instance 

1)会在Instance属性被调用的时候或者之前发生吗?

2) 有时我需要强制类创建新内存以清除其内容。使用 set 这样做安全吗?

set
{
instance = null;
}

最佳答案

在您提供的示例代码中,单例实例将在第一次访问该类时创建。这意味着您的示例在 Instance 第一次被调用时。

您可以在 Jon Skeet 的文章 Implementing the Singleton Pattern in C# 中找到更多见解,见方法四。

基本上,为了实现真正的懒惰行为

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();

static Singleton(){}
private Singleton(){}

public static Singleton Instance
{
get { return instance; }
}
}

足够了。

(但无论如何,可以在上述文章中找到完整且更好的概述。)

编辑
实际上,正如上述文章所述,由于 BeforeFiledInit 标记,不能保证在第一次访问时创建实例。您需要添加一个空的静态构造函数,这样可以保证它是惰性的。否则实例将在程序启动和首次访问之间的某个未指定时间创建。 (众所周知,.NET 运行时 2.0 具有更积极的策略,因此您可能不会获得惰性行为。)

引用上述文章:

The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler [...] marks all types which don't have a static constructor [...] as beforefieldinit.

编辑 2
如果您希望清理单例对象,则应将此功能包含到 Singleton 类本身中。

删除属性值将有效地使您的类不再是单例!想象一下,有人访问单例并获取单例实例。之后,您将该属性设置为 nullSingleton 类的现有对象不会消失,因为仍然有对它的引用!因此,下次您访问 Instance 属性时,将创建 Singleton 类的另一个实例。所以你失去了两件事:你的对象不再是单例(因为你有 2 个实例同时存在),内存也没有被清除。

关于c# - C# 问题中的单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6278088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com