ActivatorExt.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. namespace Quadarax.Foundation.Core.Reflection.Extensions
  3. {
  4. public static class ActivatorExt
  5. {
  6. #region *** Private Fields ***
  7. #endregion
  8. #region *** Public Properties ***
  9. #endregion
  10. #region *** Constructors ***
  11. #endregion
  12. #region *** Public operations & overrides ***
  13. public static object? CreateInstance(string sClassOrInterfaceQualifiedName, bool bLoadAssemblyIfNeeded, params object[] aConstructorParams)
  14. {
  15. var oType = Type.GetType(sClassOrInterfaceQualifiedName, false) ?? TypeUtils.GetRemoteType(sClassOrInterfaceQualifiedName);
  16. if (oType == null) return null;
  17. if (oType.IsInterface)
  18. {
  19. throw new ArgumentException($"Input class name '{sClassOrInterfaceQualifiedName}' cannot be an interface.",nameof(sClassOrInterfaceQualifiedName));
  20. }
  21. return Activator.CreateInstance(oType, aConstructorParams);
  22. }
  23. public static T CreateInstance<T>(string sClassOrInterfaceQualifiedName, bool bLoadAssemblyIfNeeded, params object[] aConstructorParams)
  24. {
  25. return (T) CreateInstance(sClassOrInterfaceQualifiedName, bLoadAssemblyIfNeeded, aConstructorParams)!;
  26. }
  27. #endregion
  28. #region *** Private operations & overrides ***
  29. #endregion
  30. }
  31. }