Advertisement
Guest User

PARSE_ALL

a guest
Jan 19th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Checker
  4. {
  5. public static class InputChecker
  6. {
  7. /// <summary>
  8. /// Checks if inputed value meets the conditions.
  9. /// </summary>
  10. /// <returns><c>true</c>, if value met the conditions, <c>false</c> otherwise.</returns>
  11. /// <param name="input">Input.</param>
  12. /// <param name="conditions">Conditions.</param>
  13. public static bool CheckConditions<T>(T input, params Func<T, bool>[] conditions)
  14. {
  15. foreach (Func<T, bool> condition in conditions)
  16. {
  17. if (!condition.Invoke(input))
  18. return false;
  19. }
  20. return true;
  21. }
  22.  
  23. /// <summary>
  24. /// Inputs and parses the variable of type T.
  25. /// </summary>
  26. /// <returns>Variable of type T.</returns>
  27. /// <param name="input">Input.</param>
  28. /// <param name="conditions">Conditions.</param>
  29. public static T InputVar<T>(string input, params Func<T, bool>[] conditions)
  30. {
  31. var parser = typeof(T).GetMethod("TryParse", new[] { typeof(string), typeof(T).MakeByRefType() });
  32. if (parser == null)
  33. throw new ApplicationException($"Invalid type {typeof(T)}");
  34. Console.Write($"Enter {input}: ");
  35. object[] result = { Console.ReadLine(), null};
  36. while (!(bool)parser.Invoke(null, result) || !CheckConditions((T)result[1], conditions))
  37. {
  38. Console.WriteLine("Invalid input format! Try again!");
  39. Console.Write($"Enter {input}: ");
  40. result = new object[] { Console.ReadLine(), null };
  41. }
  42. return (T)result[1];
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement