MethodDescriptor.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Jint.Runtime.Interop
  5. {
  6. internal class MethodDescriptor
  7. {
  8. private MethodDescriptor(MethodBase method)
  9. {
  10. Method = method;
  11. Parameters = method.GetParameters();
  12. foreach (var parameter in Parameters)
  13. {
  14. if (Attribute.IsDefined(parameter, typeof(ParamArrayAttribute)))
  15. {
  16. HasParams = true;
  17. break;
  18. }
  19. if (parameter.HasDefaultValue)
  20. {
  21. ParameterDefaultValuesCount++;
  22. }
  23. }
  24. }
  25. public MethodBase Method { get; }
  26. public ParameterInfo[] Parameters { get; }
  27. public bool HasParams { get; }
  28. public int ParameterDefaultValuesCount { get; }
  29. public static MethodDescriptor[] Build<T>(List<T> source) where T : MethodBase
  30. {
  31. var descriptors = new MethodDescriptor[source.Count];
  32. for (var i = 0; i < source.Count; i++)
  33. {
  34. descriptors[i] = new MethodDescriptor(source[i]);
  35. }
  36. return Prioritize(descriptors);
  37. }
  38. public static MethodDescriptor[] Build<T>(T[] source) where T : MethodBase
  39. {
  40. var descriptors = new MethodDescriptor[source.Length];
  41. for (var i = 0; i < source.Length; i++)
  42. {
  43. descriptors[i] = new MethodDescriptor(source[i]);
  44. }
  45. return Prioritize(descriptors);
  46. }
  47. private static MethodDescriptor[] Prioritize(MethodDescriptor[] descriptors)
  48. {
  49. static int CreateComparison(MethodDescriptor d1, MethodDescriptor d2)
  50. {
  51. // put params versions to end, they can be tricky to match and can cause trouble / extra overhead
  52. if (d1.HasParams)
  53. {
  54. return 1;
  55. }
  56. if (d2.HasParams)
  57. {
  58. return -1;
  59. }
  60. // then favor less parameters
  61. if (d1.Parameters.Length > d2.Parameters.Length)
  62. {
  63. return 1;
  64. }
  65. if (d2.Parameters.Length > d1.Parameters.Length)
  66. {
  67. return -1;
  68. }
  69. return 0;
  70. }
  71. Array.Sort(descriptors, CreateComparison);
  72. return descriptors;
  73. }
  74. }
  75. }