MethodInfoFunctionInstance.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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.Options.GetTypeConverter().Convert(
  39. arguments[i].ToObject(),
  40. parameterType,
  41. CultureInfo.InvariantCulture);
  42. }
  43. }
  44. var result = JsValue.FromObject(Engine, method.Invoke(thisObject.ToObject(), parameters.ToArray()));
  45. // todo: cache method info
  46. return result;
  47. }
  48. catch
  49. {
  50. // ignore method
  51. }
  52. }
  53. throw new JavaScriptException(Engine.TypeError, "No public methods with the specified arguments were found.");
  54. }
  55. }
  56. }