一般代码:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return SingletonCreator.instance;
}
}
class SingletonCreator
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}用模板实现:
public class SingletonProvider <T> where T:new()
{
SingletonProvider() {}
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}用例:
public class TestClass
{
private string _createdTimestamp;
public TestClass ()
{
_createdTimestamp = DateTime.Now.ToString();
}
public void Write()
{
Debug.WriteLine(_createdTimestamp);
}
}使用:
SingletonProvider<TestClass>.Instance.Write();
原地址:
本文介绍了一种在C#中实现单例模式的方法,包括使用密封类和静态内部类来确保实例唯一性,并提供了通用的单例模式实现模板。
965

被折叠的 条评论
为什么被折叠?



