IndexDescriptor.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Jint.Native;
  6. namespace Jint.Runtime.Descriptors.Specialized
  7. {
  8. public sealed class IndexDescriptor : PropertyDescriptor
  9. {
  10. private readonly Engine _engine;
  11. private readonly object _key;
  12. private readonly object _item;
  13. private readonly PropertyInfo _indexer;
  14. public IndexDescriptor(Engine engine, string key, object item)
  15. {
  16. _engine = engine;
  17. _item = item;
  18. // get all instance indexers with exactly 1 argument
  19. var indexers = item
  20. .GetType()
  21. .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
  22. .Where(x => x.GetIndexParameters().Length == 1);
  23. // try to find first indexer having either public getter or setter with matching argument type
  24. foreach (var indexer in indexers)
  25. {
  26. if (indexer.GetGetMethod() != null || indexer.GetSetMethod() != null)
  27. {
  28. var paramType = indexer.GetIndexParameters()[0].ParameterType;
  29. try
  30. {
  31. _key = _engine.Options.GetTypeConverter().Convert(key, paramType, CultureInfo.InvariantCulture);
  32. _indexer = indexer;
  33. break;
  34. }
  35. catch { }
  36. }
  37. }
  38. // throw if no indexer found
  39. if(_indexer == null)
  40. throw new InvalidOperationException("No matching indexer found.");
  41. Writable = true;
  42. }
  43. public override JsValue? Value
  44. {
  45. get
  46. {
  47. var getter = _indexer.GetGetMethod();
  48. if(getter == null)
  49. throw new InvalidOperationException("Indexer has no public getter.");
  50. object[] parameters = { _key };
  51. return JsValue.FromObject(_engine, getter.Invoke(_item, parameters));
  52. }
  53. set
  54. {
  55. var setter = _indexer.GetSetMethod();
  56. if (setter == null)
  57. throw new InvalidOperationException("Indexer has no public setter.");
  58. object[] parameters = { _key, value.HasValue ? value.Value.ToObject() : null };
  59. setter.Invoke(_item, parameters);
  60. }
  61. }
  62. }
  63. }