DelegateTreeBuilder.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Terminal.Gui {
  4. /// <summary>
  5. /// Implementation of <see cref="ITreeBuilder{T}"/> that uses user defined functions
  6. /// </summary>
  7. public class DelegateTreeBuilder<T> : TreeBuilder<T> {
  8. private Func<T, IEnumerable<T>> childGetter;
  9. private Func<T, bool> canExpand;
  10. /// <summary>
  11. /// Constructs an implementation of <see cref="ITreeBuilder{T}"/> that calls the user
  12. /// defined method <paramref name="childGetter"/> to determine children
  13. /// </summary>
  14. /// <param name="childGetter"></param>
  15. /// <returns></returns>
  16. public DelegateTreeBuilder (Func<T, IEnumerable<T>> childGetter) : base (false)
  17. {
  18. this.childGetter = childGetter;
  19. }
  20. /// <summary>
  21. /// Constructs an implementation of <see cref="ITreeBuilder{T}"/> that calls the user
  22. /// defined method <paramref name="childGetter"/> to determine children
  23. /// and <paramref name="canExpand"/> to determine expandability
  24. /// </summary>
  25. /// <param name="childGetter"></param>
  26. /// <param name="canExpand"></param>
  27. /// <returns></returns>
  28. public DelegateTreeBuilder (Func<T, IEnumerable<T>> childGetter, Func<T, bool> canExpand) : base (true)
  29. {
  30. this.childGetter = childGetter;
  31. this.canExpand = canExpand;
  32. }
  33. /// <summary>
  34. /// Returns whether a node can be expanded based on the delegate passed during construction
  35. /// </summary>
  36. /// <param name="toExpand"></param>
  37. /// <returns></returns>
  38. public override bool CanExpand (T toExpand)
  39. {
  40. return canExpand?.Invoke (toExpand) ?? base.CanExpand (toExpand);
  41. }
  42. /// <summary>
  43. /// Returns children using the delegate method passed during construction
  44. /// </summary>
  45. /// <param name="forObject"></param>
  46. /// <returns></returns>
  47. public override IEnumerable<T> GetChildren (T forObject)
  48. {
  49. return childGetter.Invoke (forObject);
  50. }
  51. }
  52. }