我需要一个单例代码。我读乔恩斯基特的page对单身和选择这种模式(#4)根据他的建议:基于Jon Skeet的Singleton的Simpleton Singleton
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton(){}
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
然后,我通过几个步骤去修改这个适合我的情况:
第1步:我不需要一个懒惰的实现,所以我拿出静态构造函数(如由Jon在他的文章的末尾建议):
步骤2:我再换出了“实例” Singleton
类与Logging
类我一起工作:
public sealed class Singleton
{
private static readonly Logging instance = new Logging();
private Singleton(){}
public static Logging Instance
{
get
{
return instance;
}
}
}
步骤3: ReSharper的,然后告诉我,我应该使用自动属性我的“实例”属性:
public sealed class Singleton
{
private Singleton(){}
public static Logging Instance { get; } = new Logging();
}
第4步: ReSharper的,然后告诉我,我应该关掉这个静态类:
public static class Singleton
{
public static Logging Instance { get; } = new Logging();
}
我留下的东西与原来的很不一样。我知道在设置一个线程安全的Singleton时很容易出错。
所以我想问:我的任何一个步骤是否使我的课不再是一个很好的Singleton实现?
这根本不是Singleton实现。你创建的只是**另一个**类型的共享静态变量。 –