C# 我应该把我的代码放在什么地方?

C# 我应该把我的代码放在什么地方?,c#,.net,design-patterns,singleton,C#,.net,Design Patterns,Singleton,我将链接到以下问题--> 特别是Jon Skeet的代码: public sealed class Singleton { private static readonly Singleton instance = new Singleton(); public static Singleton Instance { get { return instance; } } static Singleton() {} private Singleton()

我将链接到以下问题--> 特别是Jon Skeet的代码:

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

     static Singleton() {}
     private Singleton() {}
 }
我想知道的是,在初始化过程中,我将把需要的逻辑放在哪里?私有构造函数还是静态构造函数?从逻辑上讲,我的Singleton是我的DapperLite连接,因此我需要初始化映射,如下所示:

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


编辑:我坚持使用Compact Framework 3.5和VS 2008作为参考。

这里是Jon Skeet书中的链接

如果您使用的是.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
        }
    }
公共密封类单例
{
私有静态只读惰性=
新的懒惰(()=>newsingleton());
公共静态单例实例{get{return lazy.Value;}}
私人单身人士()
{
尝试
{
数据库=新的SqliteDatabase(myConn);
Database.Init();
}
捕获(例外情况除外)
{
//处理错误
}
}
}

编辑: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;
        }
    }
}
公共密封类单例
{
私有静态只读单例实例=新单例();
//显式静态构造函数告诉C#编译器
//不将类型标记为beforefieldinit
静态单态()
{
}
私人单身人士()
{
尝试
{
数据库=新的SqliteDatabase(myConn);
Database.Init();
}
捕获(例外情况除外)
{
//处理错误
}
}
公共静态单例实例
{
得到
{
返回实例;
}
}
}

如果类中需要任何静态字段,则应在此构造函数中初始化该字段。
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();
}
private Singleton()
{
数据库=新的SqliteDatabase(myConn);
Database.Init();
}

Doh,谢谢。很抱歉我问了个“懒惰”的问题。作为跟进,我不能使用.NET4…@RefractedPaladin:在你的问题中包含如此重要的细节总是一个好主意。我建议将其编辑到您的问题中,并提及您可以使用的.net版本。此外,为了更直接地回答您的问题,如果您需要在任何时候引用该连接,您应该在实例构造函数中进行初始化(尽管您确实不应该让它保持打开状态)。否则,我认为这是一个偏好问题,但我仍然更喜欢在实例构造函数中使用它。@tencntraze,似乎知道如何在两个构造函数中编写代码。他的问题是他到底需要写在哪里。如果他将db初始化放在静态构造函数中,到底有什么问题?@Jimmy这没有问题,所以我在你的评论上面加了我的评论。注意线程安全的需要。如果在多线程环境中使用单实例,则必须考虑到这一点@K.B,如果静态构造函数中存在数据库初始化,会有什么区别?@roryap:使用静态构造函数使其线程安全。请参见()@Jimmy——对,但此答案使用实例构造函数。