2014-02-07 110 views
4

我鏈接到以下問題 - >https://stackoverflow.com/a/2550935/46724 專門喬恩斯基特代碼:我在哪裏把我的代碼放在Singleton中?

public sealed class Singleton 
{ 
    private static readonly Singleton instance = new Singleton(); 
    public static Singleton Instance { get { return instance; } } 

    static Singleton() {} 
    private Singleton() {} 
} 

我想知道的是,我會把我需要初始化任何邏輯?私有或靜態構造函數?通過邏輯,我是說我單身我DapperLite連接,所以我需要初始化像這樣的映射:

Database = new SqliteDatabase<int>(myConn); 
Database.Init(); 

編輯:我被困在Compact Framework的3.5和VS 2008以供參考。

回答

0

下面是喬恩斯基特的書C# in Depth

鏈接如果您使用.NET 4.0:

public sealed class Singleton 
{ 
    private static readonly Lazy<Singleton> lazy = 
     new Lazy<Singleton>(() => new Singleton()); 

    public static Singleton Instance { get { return lazy.Value; } } 

    private Singleton() 
    { 
     try 
     { 
      Database = new SqliteDatabase<int>(myConn); 
      Database.Init(); 
     } 
     catch(Exception ex) 
     { 
      // Handle errors 
     } 
    } 

}

編輯:4.0版本之前的,解決方案#4從所提供的鏈接。他的首選解決方案是無需鎖的完全線程安全。

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() 
    { 
     try 
     { 
      Database = new SqliteDatabase<int>(myConn); 
      Database.Init(); 
     } 
     catch (Exception ex) 
     { 
      // Handle errors 
     } 
    } 

    public static Singleton Instance 
    { 
     get 
     { 
      return instance; 
     } 
    } 
} 
+0

衛生署,謝謝。很抱歉,「懶惰」的問題顯而易見。作爲後續,我不能使用.net 4 ... –

+1

@RefractedPaladin:在您的問題中包含這些重要細節總是一個好主意。我建議將其編輯到您的問題中,並提供您可以使用的.net版本。 –

+0

@RefractedPaladin更新爲4.0以前的編輯 – Matt

1

如果你在你的類所需要的靜態字段應該在此構造static Singleton() {}初始化爲其他實例字段或屬性它應該去private Singleton() {} 更多的看看下面的代碼

public class Bus 
    { 
     // Static variable used by all Bus instances. 
     // Represents the time the first bus of the day starts its route. 
     protected static readonly DateTime globalStartTime; 

     // Property for the number of each bus. 
     protected int RouteNumber { get; set; } 

     // Static constructor to initialize the static variable. 
     // It is invoked before the first instance constructor is run. 
     static Bus() 
     { 
      globalStartTime = DateTime.Now; 

      // The following statement produces the first line of output, 
      // and the line occurs only once. 
      Console.WriteLine("Static constructor sets global start time to {0}", 
       globalStartTime.ToLongTimeString()); 
     } 

     // Instance constructor. 
     public Bus(int routeNum) 
     { 
      RouteNumber = routeNum; 
      Console.WriteLine("Bus #{0} is created.", RouteNumber); 
     } 

     // Instance method. 
     public void Drive() 
     { 
      TimeSpan elapsedTime = DateTime.Now - globalStartTime; 

      // For demonstration purposes we treat milliseconds as minutes to simulate 
      // actual bus times. Do not do this in your actual bus schedule program! 
      Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.", 
            this.RouteNumber, 
            elapsedTime.TotalMilliseconds, 
            globalStartTime.ToShortTimeString()); 
     } 
    } 

    class TestBus 
    { 
     static void Main() 
     { 
      // The creation of this instance activates the static constructor. 
      Bus bus1 = new Bus(71); 

      // Create a second bus. 
      Bus bus2 = new Bus(72); 

      // Send bus1 on its way. 
      bus1.Drive(); 

      // Wait for bus2 to warm up. 
      System.Threading.Thread.Sleep(25); 

      // Send bus2 on its way. 
      bus2.Drive(); 

      // Keep the console window open in debug mode. 
      System.Console.WriteLine("Press any key to exit."); 
      System.Console.ReadKey(); 
     } 
    } 

所以你的情況是一個實例初始化

private Singleton() 
{ 
Database = new SqliteDatabase<int>(myConn); 
Database.Init(); 
} 
+0

請注意線程安全的需求。如果你在多線程環境中使用你的單例,你必須考慮到這一點。 http://msdn.microsoft.com/en-us/library/ff650316.aspx –

+0

@ K.B,如果數據庫初始化存在於靜態構造函數中,會有什麼不同? – Jimmy

+0

@ roryap:靜態構造函數的使用使其線程安全。請參閱(http://csharpindepth.com/Articles/General/Singleton.aspx) – Jimmy

相關問題