c# - 我应该把我的代码放在 Singleton 中的什么地方?

标签 c# .net design-patterns singleton

我正在链接到以下问题 --> https://stackoverflow.com/a/2550935/46724 特别是 Jon Skeet 的代码:

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

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

我想知道的是,我应该把初始化所需的任何逻辑放在哪里?私有(private)或静态构造函数?按照逻辑,我的意思是我的 Singleton 是我的 DapperLite 连接,所以我需要像这样初始化映射:

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

编辑:我坚持使用 Compact Framework 3.5 和 VS 2008 以供引用。

最佳答案

如果你的类中有任何需要的静态字段,它应该在这个构造函数中初始化 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();
}

关于c# - 我应该把我的代码放在 Singleton 中的什么地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21630113/

相关文章:

c# - 第二个参数干扰通用处理程序

.net - 进行大量细化后,如何“避免”应用程序不响应?

java - 作为接口(interface)实现的抽象工厂模式

Java 原型(prototype)克隆没有按预期工作?

c# - 静态方法与单例

c# - 在不使用 Windows 窗体中的事件的情况下检测是否按下了 Shift 键?

C#/.Net 使用 ThreadLocal 和 Async/Await

c# - 在 Windows 10 通用 Windows 库中引用 BindingFlags 类型时无法加载程序集

c# - 更改 DataTable 列中每个单元格的值

java - 尽量减少类中的代码重复?