SafeConsole.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 ConsoleColor BackgroundColor
  19. {
  20. get { return _getBackgroundColor(); }
  21. set { _setBackgroundColor(value); }
  22. }
  23. public static ConsoleColor ForegroundColor
  24. {
  25. get { return _getForegroundColor(); }
  26. set { _setForegroundColor(value); }
  27. }
  28. static SafeConsole()
  29. {
  30. var tConsole = typeof(Console);
  31. InitColors(tConsole);
  32. }
  33. private static void InitColors(Type tConsole)
  34. {
  35. const BindingFlags BINDING_FLAGS = BindingFlags.Public | BindingFlags.Static;
  36. var sfc = tConsole.GetMethod("set_ForegroundColor", BINDING_FLAGS);
  37. var sbc = tConsole.GetMethod("set_BackgroundColor", BINDING_FLAGS);
  38. var gfc = tConsole.GetMethod("get_ForegroundColor", BINDING_FLAGS);
  39. var gbc = tConsole.GetMethod("get_BackgroundColor", BINDING_FLAGS);
  40. _setForegroundColor = sfc != null
  41. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sfc)
  42. : (value => { });
  43. _setBackgroundColor = sbc != null
  44. ? (SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), sbc)
  45. : (value => { });
  46. _getForegroundColor = gfc != null
  47. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gfc)
  48. : (() => ConsoleColor.Gray);
  49. _getBackgroundColor = gbc != null
  50. ? (GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), gbc)
  51. : (() => ConsoleColor.Black);
  52. }
  53. private delegate ConsoleColor GetColorDelegate();
  54. private delegate void SetColorDelegate(ConsoleColor value);
  55. }
  56. }