NamespaceReference.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Jint.Native;
  6. using Jint.Native.Object;
  7. using Jint.Runtime.Descriptors;
  8. namespace Jint.Runtime.Interop
  9. {
  10. /// <summary>
  11. /// Any instance on this class represents a reference to a CLR namespace.
  12. /// Accessing its properties will look for a class of the full name, or instantiate
  13. /// a new <see cref="NamespaceReference"/> as it assumes that the property is a deeper
  14. /// level of the current namespace
  15. /// </summary>
  16. public class NamespaceReference : ObjectInstance
  17. {
  18. private readonly string _path;
  19. public NamespaceReference(Engine engine, string path) : base(engine)
  20. {
  21. _path = path;
  22. }
  23. public override bool DefineOwnProperty(string propertyName, PropertyDescriptor desc, bool throwOnError)
  24. {
  25. if (throwOnError)
  26. {
  27. throw new JavaScriptException(Engine.TypeError, "Can't define a property of a NamespaceReference");
  28. }
  29. return false;
  30. }
  31. public override bool Delete(string propertyName, bool throwOnError)
  32. {
  33. if (throwOnError)
  34. {
  35. throw new JavaScriptException(Engine.TypeError, "Can't delete a property of a NamespaceReference");
  36. }
  37. return false;
  38. }
  39. public override JsValue Get(string propertyName)
  40. {
  41. var newPath = _path + "." + propertyName;
  42. var type = Type.GetType(newPath);
  43. if (type != null)
  44. {
  45. return TypeReference.CreateTypeReference(Engine, type);
  46. }
  47. // the new path doesn't represent a known class, thus return a new namespace instance
  48. return new NamespaceReference(Engine, newPath);
  49. }
  50. public override PropertyDescriptor GetOwnProperty(string propertyName)
  51. {
  52. return PropertyDescriptor.Undefined;
  53. }
  54. public override string ToString()
  55. {
  56. return "[Namespace: " + _path + "]";
  57. }
  58. }
  59. }