星空网 > 软件开发 > ASP.net

NopCommerce中的单例

项目中经常会遇到单例的情况。大部分的单例代码都差不多像这样定义:

internal class SingletonOne  {    private static SingletonOne _singleton;    private SingletonOne()    {    }    public static SingletonOne Instance    {      get      {        if (_singleton == null)        {          var instance = new SingletonOne();          Interlocked.CompareExchange(ref _singleton, instance, null);        }        return _singleton;      }    }  }

但是很明显的一个缺点是这个类只能用作单例。

最近看了NopCommerce对单例有个包装。觉得有点新颖 给大家分享一下。

/// <summary>  /// Provides access to all "singletons" stored by <see cref="Singleton{T}"/>.  /// </summary>  public class Singleton  {    static Singleton()    {      allSingletons = new Dictionary<Type, object>();    }    static readonly IDictionary<Type, object> allSingletons;    /// <summary>Dictionary of type to singleton instances.</summary>    public static IDictionary<Type, object> AllSingletons    {      get { return allSingletons; }    }  }

public class Singleton<T> : Singleton  {    static T instance;    /// <summary>The singleton instance for the specified type T. Only one instance (at the time) of this object for each type of T.</summary>    public static T Instance    {      get { return instance; }      set      {        instance = value;        AllSingletons[typeof(T)] = value;      }    }  }

比如定义了一个类, 那么可以这样使用

public class Fake{}Singleton<Fake>.Instance = new Fake();




原标题:NopCommerce中的单例

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

如何外国期货开户:https://www.goluckyvip.com/tag/72851.html
境外投资开户:https://www.goluckyvip.com/tag/72852.html
海外开户见证业务:https://www.goluckyvip.com/tag/72855.html
个人开立境外账户:https://www.goluckyvip.com/tag/72856.html
境外开户申请:https://www.goluckyvip.com/tag/72858.html
Amazon Posts:https://www.goluckyvip.com/tag/7286.html
斥资210万美元,TikTok游说美国参议院阻止法案:https://www.goluckyvip.com/news/188213.html
大家推荐一下厦门三整天一个半天的旅游攻略:https://www.vstour.cn/a/365181.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流