相关疑难解决方法(0)

C#中一个好的线程安全单例通用模板模式是什么

我有以下C#单例模式,有什么方法可以改进它吗?

    public class Singleton<T> where T : class, new()
    {

        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public Singleton()
        { }

    }
Run Code Online (Sandbox Code Playgroud)

首选用法示例:

class Foo : Singleton<Foo> 
{
} 
Run Code Online (Sandbox Code Playgroud)

相关:

.NET的一个明显的单例实现?

c# design-patterns

31
推荐指数
4
解决办法
2万
查看次数

一般的单身人士

对于一般的单身人士,你们对此有何看法?

using System;
using System.Reflection;

// Use like this
/*
public class Highlander : Singleton<Highlander>
{
    private Highlander()
    {
        Console.WriteLine("There can be only one...");
    }
}
*/

public class Singleton<T> where T : class
{
    private static T instance;
    private static object initLock = new object();

    public static T GetInstance()
    {
        if (instance == null)
        {
            CreateInstance();
        }

        return instance;
    }

    private static void CreateInstance()
    {
        lock (initLock)
        {
            if (instance == null)
            {
                Type t = typeof(T);

                // Ensure …
Run Code Online (Sandbox Code Playgroud)

c# generics singleton

19
推荐指数
4
解决办法
2万
查看次数

标签 统计

c# ×2

design-patterns ×1

generics ×1

singleton ×1