HungrySingleton.cs 974 B

1234567891011121314151617181920212223242526272829303132
  1. using System;
  2. using System.Reflection;
  3. namespace Blue
  4. {
  5. public class HungrySingleton<T> where T : HungrySingleton<T>
  6. {
  7. private static T _instance = init();
  8. public static T Instance
  9. {
  10. get => _instance;
  11. }
  12. private static T init()
  13. {
  14. Type type = typeof(T);
  15. ConstructorInfo[] ctorArr = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
  16. if (ctorArr.Length == 0)
  17. {
  18. throw new Exception("Non Public Contstrucor Not Found In " + type.FullName);
  19. }
  20. ConstructorInfo ctor = Array.Find(ctorArr, c => c.GetParameters().Length == 0);
  21. if (ctor == null)
  22. {
  23. throw new Exception("Non Public Contstrucor Not Found In " + type.FullName);
  24. }
  25. _instance = ctor.Invoke(null) as T;
  26. return _instance;
  27. }
  28. }
  29. }