2
0

MethodInfoFunctionInstance.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. parameters[i] = Engine.Options.GetTypeConverter().Convert(
  32. arguments[i].ToObject(),
  33. method.GetParameters()[i].ParameterType,
  34. CultureInfo.InvariantCulture);
  35. }
  36. var result = JsValue.FromObject(Engine, method.Invoke(thisObject.ToObject(), parameters.ToArray()));
  37. // todo: cache method info
  38. return result;
  39. }
  40. catch
  41. {
  42. // ignore method
  43. }
  44. }
  45. throw new JavaScriptException(Engine.TypeError, "No public methods with the specified arguments were found.");
  46. }
  47. }
  48. }