You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReflectionUtils.cs 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. namespace Discord.Commands
  5. {
  6. internal class ReflectionUtils
  7. {
  8. internal static object CreateObject(TypeInfo typeInfo, CommandService service, IDependencyMap map = null)
  9. {
  10. var constructors = typeInfo.DeclaredConstructors.Where(x => !x.IsStatic).ToArray();
  11. if (constructors.Length == 0)
  12. throw new InvalidOperationException($"No constructor found for \"{typeInfo.FullName}\"");
  13. else if (constructors.Length > 1)
  14. throw new InvalidOperationException($"Multiple constructors found for \"{typeInfo.FullName}\"");
  15. var constructor = constructors[0];
  16. ParameterInfo[] parameters = constructor.GetParameters();
  17. object[] args = new object[parameters.Length];
  18. for (int i = 0; i < parameters.Length; i++)
  19. {
  20. var parameter = parameters[i];
  21. object arg;
  22. if (map == null || !map.TryGet(parameter.ParameterType, out arg))
  23. {
  24. if (parameter.ParameterType == typeof(CommandService))
  25. arg = service;
  26. else if (parameter.ParameterType == typeof(IDependencyMap))
  27. arg = map;
  28. else
  29. throw new InvalidOperationException($"Failed to create \"{typeInfo.FullName}\", dependency \"{parameter.ParameterType.Name}\" was not found.");
  30. }
  31. args[i] = arg;
  32. }
  33. try
  34. {
  35. return constructor.Invoke(args);
  36. }
  37. catch (Exception ex)
  38. {
  39. throw new Exception($"Failed to create \"{typeInfo.FullName}\"", ex);
  40. }
  41. }
  42. }
  43. }