NamespaceReference.cs 2.8 KB

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