用 C# 实现的单例可能是这样的:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
如果我使用 static 来实现它:
public static class Globals{
public static Singleton Instance = new Singleton();
}
这样一来,应用程序也应该只获取整个应用程序的一个实例。 那么这两种方法有什么区别呢?为什么不直接使用静态成员(更简单直接)?
最佳答案
如果你使用第二种方法:
public static class Globals{
public static Singleton Instance = new Singleton();
}
没有什么能阻止某人做:
Singleton anotherInstance = new Singleton(); // Violates singleton rules
您也不会获得与您的第一个版本(尝试)实现的相同的延迟初始化,而且您使用的是公共(public)字段,如果您需要更改发生的事情,这将不允许您在未来获得相同的灵 active 获取值时。
请注意,.NET 4 提供了一种可能更好的方法来创建单例:
public class Singleton
{
private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());
private Singleton() {}
public static Singleton Instance
{
get
{
return instance.Value;
}
}
}
这很好,因为它是完全惰性的和完全线程安全的,但也很简单。
关于c# - 静态属性和单例有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678305/