Singleton.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. /// <summary>
  4. /// 普通单例
  5. /// </summary>
  6. /// <typeparam name="T"></typeparam>
  7. public class Singleton<T> where T : Singleton<T>, new()
  8. {
  9. /// <summary>
  10. /// 单例
  11. /// </summary>
  12. private static T m_Instance;
  13. /// <summary>
  14. /// 实例
  15. /// </summary>
  16. public static T Instance
  17. {
  18. get
  19. {
  20. if (object.ReferenceEquals(Singleton<T>.m_Instance, null))
  21. {
  22. var obj = new T();
  23. Singleton<T>.m_Instance = obj;
  24. Container.Add(typeof(T).Name, obj);
  25. }
  26. return Singleton<T>.m_Instance;
  27. }
  28. }
  29. /// <summary>
  30. /// 新能剖析方法,
  31. /// </summary>
  32. /// <returns>返回每个单例占用的内存大小</returns>
  33. [Obsolete("没有意义,需要不断的遍历引用直到基础类型才能确定最终大小,-wg 2019年10月23日 11:42:21")]
  34. public static Dictionary<string, int> Profile_Size()
  35. {
  36. var dic = new Dictionary<string, int>();
  37. //foreach (var itc in Container) {
  38. // // itc.Key
  39. // System.Runtime.InteropServices.Marshal.SizeOf( itc.Value)
  40. //}
  41. return dic;
  42. }
  43. #region ' 内部容器 '
  44. static Dictionary<string, Object> _mC;
  45. static Dictionary<string, Object> Container
  46. {
  47. get
  48. {
  49. if (null == _mC)
  50. {
  51. _mC = new Dictionary<string, object>();
  52. }
  53. return _mC;
  54. }
  55. }
  56. #endregion
  57. }