SafeConsole.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // --------------------------------------------------
  2. // UnityInjector - SafeConsole.cs
  3. // Copyright (c) Usagirei 2015 - 2015
  4. // --------------------------------------------------
  5. using System;
  6. using System.Reflection;
  7. namespace UnityInjector.ConsoleUtil
  8. {
  9. /// <summary>
  10. /// Console class required for Unity 4.x, which do not have ForegroundColor and BackgroundColor properties
  11. /// </summary>
  12. internal static class SafeConsole
  13. {
  14. private static GetColorDelegate _getBackgroundColor;
  15. private static GetColorDelegate _getForegroundColor;
  16. private static SetColorDelegate _setBackgroundColor;
  17. private static SetColorDelegate _setForegroundColor;
  18. public static bool BackgroundColorExists { get; private set; }
  19. public static ConsoleColor BackgroundColor
  20. {
  21. get => _getBackgroundColor();
  22. set => _setBackgroundColor(value);
  23. }
  24. public static bool ForegroundColorExists { get; private set; }
  25. public static ConsoleColor ForegroundColor
  26. {
  27. get => _getForegroundColor();
  28. set => _setForegroundColor(value);
  29. }
  30. static SafeConsole()
  31. {
  32. var tConsole = typeof(Console);
  33. InitColors(tConsole);
  34. }
  35. private static void InitColors(Type tConsole)
  36. {
  37. const BindingFlags BINDING_FLAGS = BindingFlags.Public | BindingFlags.Static;
  38. var sfc = tConsole.GetMethod("set_ForegroundColor", BINDING_FLAGS);
  39. var sbc = tConsole.GetMethod("set_BackgroundColor", BINDING_FLAGS);
  40. var gfc = tConsole.GetMethod("get_ForegroundColor", BINDING_FLAGS);
  41. var gbc = tConsole.GetMethod("get_BackgroundColor", BINDING_FLAGS);
  42. _setForegroundColor = sfc != null
  43. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sfc)
  44. : (value => { });
  45. _setBackgroundColor = sbc != null
  46. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sbc)
  47. : (value => { });
  48. _getForegroundColor = gfc != null
  49. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gfc)
  50. : (() => ConsoleColor.Gray);
  51. _getBackgroundColor = gbc != null
  52. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gbc)
  53. : (() => ConsoleColor.Black);
  54. BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null;
  55. ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null;
  56. }
  57. private delegate ConsoleColor GetColorDelegate();
  58. private delegate void SetColorDelegate(ConsoleColor value);
  59. }
  60. }