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 2.2 kB

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