MethodInfoFunctionInstance.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Globalization;
  2. using System.Linq;
  3. using System.Reflection;
  4. using Jint.Native;
  5. using Jint.Native.Function;
  6. namespace Jint.Runtime.Interop
  7. {
  8. public sealed class MethodInfoFunctionInstance : FunctionInstance
  9. {
  10. private readonly MethodInfo[] _methods;
  11. public MethodInfoFunctionInstance(Engine engine, MethodInfo[] methods)
  12. : base(engine, null, null, false)
  13. {
  14. _methods = methods;
  15. Prototype = engine.Function.PrototypeObject;
  16. }
  17. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  18. {
  19. return Invoke(_methods, thisObject, arguments);
  20. }
  21. public JsValue Invoke(MethodInfo[] methodInfos, JsValue thisObject, JsValue[] arguments)
  22. {
  23. var methods = TypeConverter.FindBestMatch(Engine, methodInfos, arguments).ToList();
  24. foreach (var method in methods)
  25. {
  26. var parameters = new object[arguments.Length];
  27. try
  28. {
  29. for (var i = 0; i < arguments.Length; i++)
  30. {
  31. var parameterType = method.GetParameters()[i].ParameterType;
  32. if (parameterType == typeof(JsValue))
  33. {
  34. parameters[i] = arguments[i];
  35. }
  36. else
  37. {
  38. parameters[i] = Engine.ClrTypeConverter.Convert(
  39. arguments[i].ToObject(),
  40. parameterType,
  41. CultureInfo.InvariantCulture);
  42. if (typeof(System.Linq.Expressions.LambdaExpression).IsAssignableFrom(parameters[i].GetType()))
  43. {
  44. parameters[i] = (parameters[i] as System.Linq.Expressions.LambdaExpression).Compile();
  45. }
  46. }
  47. }
  48. var result = JsValue.FromObject(Engine, method.Invoke(thisObject.ToObject(), parameters.ToArray()));
  49. // todo: cache method info
  50. return result;
  51. }
  52. catch
  53. {
  54. // ignore method
  55. }
  56. }
  57. throw new JavaScriptException(Engine.TypeError, "No public methods with the specified arguments were found.");
  58. }
  59. }
  60. }