日期:2014-05-17 浏览次数:21301 次
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();