Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. using System;
  2.  
  3. public class IncrementalSelection<T> where T : struct, IConvertible // reject all types other than enum
  4. {
  5. public T selectedItem{ get; private set;}
  6.  
  7. public IncrementalSelection(T initialSelection)
  8. {
  9. if (!typeof(T).IsEnum)
  10. {
  11. throw new ArgumentException("T must be an enumerated type"); // reject all types other than enum
  12. }
  13. selectedItem = initialSelection;
  14. }
  15.  
  16. public void Increment()
  17. {
  18. selectedItem = (T)(object)(((int)(object)selectedItem)+1);
  19. if((int)(object)selectedItem >= Enum.GetNames(typeof(T)).Length)
  20. {
  21. selectedItem = (T)Enum.GetValues(typeof(T)).GetValue(0);
  22. }
  23. }
  24. }
  25.  
  26. public class Program
  27. {
  28. enum Focus {
  29. Narrow,
  30. Normal,
  31. Wide
  32. };
  33.  
  34. public static void Main()
  35. {
  36. var focus = new IncrementalSelection<Focus>(Focus.Normal);
  37.  
  38. System.Console.WriteLine(Enum.GetName(typeof(Focus), focus.selectedItem));
  39. focus.Increment();
  40.  
  41. System.Console.WriteLine(Enum.GetName(typeof(Focus), focus.selectedItem));
  42. focus.Increment();
  43.  
  44. System.Console.WriteLine(Enum.GetName(typeof(Focus), focus.selectedItem));
  45. focus.Increment();
  46.  
  47. System.Console.WriteLine(Enum.GetName(typeof(Focus), focus.selectedItem));
  48. focus.Increment();
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement