我看到了这样的实现:
class MyClass
{
private static readonly MyClass _instance = new MyClass();
public static MyClass Instance{
get{ return _instance; }
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不简单?
class MyClass
{
public static readonly MyClass Instance = new MyClass();
}
Run Code Online (Sandbox Code Playgroud)
您可以公开这样的公共字段 - 但我不愿意.如果将其保留为属性,则可以稍后更改实现.例如,假设您稍后添加了一个静态方法,您想要在不初始化单例的情况下调用它 - 使用属性版本,您可以将代码更改为:
public sealed class MyClass
{
public static MyClass Instance { get { return InstanceHolder.instance; } }
private MyClass() {}
private static class InstanceHolder
{
internal static readonly MyClass instance = new MyClass();
}
public static void Foo()
{
// Calling this won't initialize the singleton
}
}
Run Code Online (Sandbox Code Playgroud)
(对于原始版本,单例可能已初始化,或者可能不是 - 它取决于CLR.)
这只是您可能希望稍后更改实现的一个示例.有了房产,你就可以做到 - 有了田地,你就做不到.