PropertyInfoDescriptor.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Globalization;
  2. using System.Reflection;
  3. using Jint.Native;
  4. namespace Jint.Runtime.Descriptors.Specialized
  5. {
  6. public sealed class PropertyInfoDescriptor : PropertyDescriptor
  7. {
  8. private readonly Engine _engine;
  9. private readonly PropertyInfo _propertyInfo;
  10. private readonly object _item;
  11. public PropertyInfoDescriptor(Engine engine, PropertyInfo propertyInfo, object item) : base(PropertyFlag.CustomJsValue)
  12. {
  13. _engine = engine;
  14. _propertyInfo = propertyInfo;
  15. _item = item;
  16. Writable = propertyInfo.CanWrite;
  17. }
  18. protected internal override JsValue CustomValue
  19. {
  20. get => JsValue.FromObject(_engine, _propertyInfo.GetValue(_item, null));
  21. set
  22. {
  23. var currentValue = value;
  24. object obj;
  25. if (_propertyInfo.PropertyType == typeof (JsValue))
  26. {
  27. obj = currentValue;
  28. }
  29. else
  30. {
  31. // attempt to convert the JsValue to the target type
  32. obj = currentValue.ToObject();
  33. if (obj != null && obj.GetType() != _propertyInfo.PropertyType)
  34. {
  35. obj = _engine.ClrTypeConverter.Convert(obj, _propertyInfo.PropertyType, CultureInfo.InvariantCulture);
  36. }
  37. }
  38. _propertyInfo.SetValue(_item, obj, null);
  39. }
  40. }
  41. }
  42. }