一般代码:
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();
原地址: