Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.6KB

  1. using System;
  2. using System.Reflection;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. public struct WeakAction<T1, T2>:IEquatable<WeakAction<T1, T2>>
  6. {
  7. public WeakAction(Action<T1, T2> listener)
  8. {
  9. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  10. Method = listener.Method;
  11. if (Method.DeclaringType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length != 0)
  12. throw new ArgumentException("Cannot create weak event to anonymous method with closure.");
  13. }
  14. public bool Invoke(T1 data1, T2 data2)
  15. {
  16. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  17. {
  18. Method.Invoke(ObjectRef.Target, new object[] { data1, data2 });
  19. return true;
  20. }
  21. return false;
  22. }
  23. public bool Equals(WeakAction<T1, T2> other)
  24. {
  25. return (Method.Equals(other.Method));
  26. }
  27. readonly GCHandle ObjectRef;
  28. readonly MethodInfo Method;
  29. }
  30. public struct WeakAction<T>:IEquatable<WeakAction<T>>
  31. {
  32. public WeakAction(Action<T> listener)
  33. {
  34. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  35. Method = listener.Method;
  36. if (Method.DeclaringType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length != 0)
  37. throw new ArgumentException("Cannot create weak event to anonymous method with closure.");
  38. }
  39. public bool Invoke(T data)
  40. {
  41. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  42. {
  43. Method.Invoke(ObjectRef.Target, new object[] { data });
  44. return true;
  45. }
  46. return false;
  47. }
  48. public bool Equals(WeakAction<T> other)
  49. {
  50. return (Method.Equals(other.Method));
  51. }
  52. readonly GCHandle ObjectRef;
  53. readonly MethodInfo Method;
  54. }
  55. public struct WeakAction:IEquatable<WeakAction>
  56. {
  57. public WeakAction(Action listener)
  58. {
  59. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  60. Method = listener.Method;
  61. if (Method.DeclaringType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length != 0)
  62. throw new ArgumentException("Cannot create weak event to anonymous method with closure.");
  63. }
  64. public bool Invoke()
  65. {
  66. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  67. {
  68. Method.Invoke(ObjectRef.Target, null);
  69. return true;
  70. }
  71. return false;
  72. }
  73. public bool Equals(WeakAction other)
  74. {
  75. return (Method.Equals(other.Method));
  76. }
  77. readonly GCHandle ObjectRef;
  78. readonly MethodInfo Method;
  79. }