Guest User

Untitled

a guest
Jun 19th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. // Quickly switch to a different culture to perform work without
  2. // switching the entire thread
  3.  
  4. // Usage:
  5. // Console.WriteLine("Starts in English : {0}", DateTime.Now);
  6. //
  7. // Culture.As(Culture.Type.German, () => {
  8. // Console.WriteLine("Now in German : {0}", DateTime.Now);
  9. // });
  10. //
  11. // Console.WriteLine("English again : {0}", DateTime.Now);
  12.  
  13.  
  14. /// <summary>
  15. /// Handles working in different cultures for periods of times
  16. /// </summary>
  17. public class Culture {
  18.  
  19. /// <summary>
  20. /// Types of cultures to use
  21. /// </summary>
  22. public enum Type {
  23. English,
  24. German,
  25. Spanish
  26. }
  27.  
  28. /// <summary>
  29. /// Performs work in a different culture
  30. /// </summary>
  31. public static void As(Culture.Type type, Action work) {
  32. string culture = Culture._GetCultureString(type);
  33. Culture.As(culture, work);
  34. }
  35.  
  36. /// <summary>
  37. /// Performs work in a different culture
  38. /// </summary>
  39. public static void As(string culture, Action work) {
  40. culture = (culture ?? string.Empty).Trim();
  41.  
  42. //get the existing cultures to revert
  43. var original = new {
  44. culture = Thread.CurrentThread.CurrentCulture,
  45. uiCulture = Thread.CurrentThread.CurrentUICulture
  46. };
  47.  
  48. //create the new cultures to use
  49. CultureInfo temporary = new CultureInfo(culture);
  50. Thread.CurrentThread.CurrentCulture = temporary;
  51. Thread.CurrentThread.CurrentUICulture = temporary;
  52.  
  53. //perform the work
  54. try { work(); }
  55. //and make sure to revert the culture
  56. finally {
  57. Thread.CurrentThread.CurrentCulture = original.culture;
  58. Thread.CurrentThread.CurrentCulture = original.uiCulture;
  59. }
  60.  
  61. }
  62.  
  63. //grabs the culture string from a type
  64. private static string _GetCultureString(Culture.Type type) {
  65. switch (type) {
  66. case Type.German: return "de-DE";
  67. case Type.Spanish: return "es-ES";
  68. //add more cultures as needed
  69. default: return "en-EN";
  70. }
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment