SingleBase.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. namespace PlcSiemens.Core.Common
  2. {
  3. /// <summary>
  4. /// 单例基类
  5. /// </summary>
  6. /// <typeparam name="T"></typeparam>
  7. public class SingleBase<T> where T : new()
  8. {
  9. // ReSharper disable once InconsistentNaming
  10. private static readonly T _instance;
  11. // ReSharper disable once StaticFieldInGenericType
  12. private static readonly object ObjLock = new object();
  13. /// <summary>
  14. /// 获取单例句柄
  15. /// </summary>
  16. public static T Instance
  17. { get { return _instance; } }
  18. static SingleBase()
  19. {
  20. if (_instance != null) return;
  21. lock (ObjLock)
  22. {
  23. if (_instance == null)
  24. {
  25. _instance = new T();
  26. }
  27. }
  28. }
  29. public SingleBase()
  30. {
  31. if (_instance != null)
  32. {
  33. throw new InvalidOperationException("单例模式设计,不允许重复实例化对象");
  34. }
  35. }
  36. }
  37. }