IWrapper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. namespace Animancer
  3. {
  4. /// <summary>An object which wraps a <see cref="WrappedObject"/> object.</summary>
  5. /// https://kybernetik.com.au/animancer/api/Animancer/IWrapper
  6. ///
  7. public interface IWrapper
  8. {
  9. /************************************************************************************************************************/
  10. /// <summary>The wrapped object.</summary>
  11. /// <remarks>
  12. /// Use <see cref="AnimancerUtilities.GetWrappedObject"/> in case the <see cref="WrappedObject"/> is also an
  13. /// <see cref="IWrapper"/>.
  14. /// </remarks>
  15. object WrappedObject { get; }
  16. /************************************************************************************************************************/
  17. }
  18. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerUtilities
  19. public static partial class AnimancerUtilities
  20. {
  21. /************************************************************************************************************************/
  22. /// <summary>Returns the <see cref="IWrapper.WrappedObject"/> recursively.</summary>
  23. public static object GetWrappedObject(object wrapper)
  24. {
  25. while (wrapper is IWrapper targetWrapper)
  26. wrapper = targetWrapper.WrappedObject;
  27. return wrapper;
  28. }
  29. /// <summary>
  30. /// Returns the `wrapper` or first <see cref="IWrapper.WrappedObject"/> which is a <typeparamref name="T"/>.
  31. /// </summary>
  32. public static bool TryGetWrappedObject<T>(object wrapper, out T wrapped) where T : class
  33. {
  34. while (true)
  35. {
  36. wrapped = wrapper as T;
  37. if (wrapped != null)
  38. return true;
  39. if (wrapper is IWrapper targetWrapper)
  40. wrapper = targetWrapper.WrappedObject;
  41. else
  42. return false;
  43. }
  44. }
  45. /************************************************************************************************************************/
  46. }
  47. }