DynamicClassInstance.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Island.StandardLib.Reflection.Exception;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. namespace Island.StandardLib.Reflection
  8. {
  9. public class DynamicClassInstance : DynamicExtendableInstance
  10. {
  11. public DynamicManager Manager { get; private set; }
  12. public DynamicType ClassType { get; private set; }
  13. public object Instance { get; private set; }
  14. public DynamicClassInstance(DynamicManager manager, DynamicType type, params object[] initargs)
  15. {
  16. Manager = manager;
  17. ClassType = type;
  18. if (initargs == null) initargs = new object[1] { null };
  19. initargs = initargs.Do(r => r is DynamicClassInstance instance ? instance.Instance : r);
  20. Instance = Activator.CreateInstance(type.ClassType, initargs);
  21. }
  22. public DynamicClassInstance(DynamicManager manager, object instance)
  23. {
  24. Manager = manager;
  25. ClassType = Manager.GetDynamicType(instance.GetType());
  26. Instance = instance;
  27. }
  28. public object Call(string methodName, params object[] args)
  29. {
  30. if (args == null) args = new object[1] { null };
  31. args = args.Do(r => r is DynamicClassInstance instance ? instance.Instance : r);
  32. foreach (var t in ClassType.FindMethod(methodName))
  33. {
  34. try
  35. {
  36. return t.Invoke(Instance, args.Length == 0 ? null : args);
  37. }
  38. catch (TargetParameterCountException)
  39. {
  40. continue;
  41. }
  42. }
  43. throw new MethodNotFoundException(ClassType.ClassType.Name, methodName);
  44. }
  45. public DynamicClassInstance CallR(string methodName, params object[] args)
  46. {
  47. return new DynamicClassInstance(Manager, Call(methodName, args));
  48. }
  49. public object this[string propertieName]
  50. {
  51. get => GetPropertie(propertieName);
  52. set => SetPropertie(propertieName, value);
  53. }
  54. public DynamicClassInstance this[string propertieName, object flag]
  55. {
  56. get => new DynamicClassInstance(Manager, GetPropertie(propertieName));
  57. set => SetPropertie(propertieName, value.Instance);
  58. }
  59. public void SetPropertie(string propertie, object value) => Call("set_" + propertie, value);
  60. public object GetPropertie(string propertie) => Call("get_" + propertie);
  61. public T As<T>() where T : class => Manager as T;
  62. }
  63. public class DynamicClassInstance<T> : DynamicClassInstance where T : class
  64. {
  65. public DynamicClassInstance(DynamicManager manager, DynamicType type, params object[] initargs)
  66. : base(manager, type, initargs) { }
  67. public static implicit operator T(DynamicClassInstance<T> instance) => instance.As<T>();
  68. }
  69. }