IniKeyExtensions.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using ExIni;
  7. namespace XUnity.AutoTranslator.Plugin.Core.Configuration
  8. {
  9. public static class IniKeyExtensions
  10. {
  11. public static T GetOrDefault<T>( this IniKey that, T defaultValue, bool allowEmpty = false )
  12. {
  13. if( !allowEmpty )
  14. {
  15. var value = that.Value;
  16. if( string.IsNullOrEmpty( value ) )
  17. {
  18. if( typeof( T ).IsEnum )
  19. {
  20. that.Value = Enum.GetName( typeof( T ), defaultValue );
  21. }
  22. else
  23. {
  24. that.Value = Convert.ToString( defaultValue, CultureInfo.InvariantCulture );
  25. }
  26. return defaultValue;
  27. }
  28. else
  29. {
  30. if( typeof( T ).IsEnum )
  31. {
  32. return (T)Enum.Parse( typeof( T ), that.Value, true );
  33. }
  34. else
  35. {
  36. return (T)Convert.ChangeType( that.Value, typeof( T ), CultureInfo.InvariantCulture );
  37. }
  38. }
  39. }
  40. else
  41. {
  42. var value = that.Value;
  43. if( value == null )
  44. {
  45. if( typeof( T ).IsEnum )
  46. {
  47. that.Value = Enum.GetName( typeof( T ), defaultValue );
  48. }
  49. else
  50. {
  51. that.Value = Convert.ToString( defaultValue, CultureInfo.InvariantCulture );
  52. }
  53. return defaultValue;
  54. }
  55. else
  56. {
  57. if( typeof( T ).IsEnum )
  58. {
  59. return (T)Enum.Parse( typeof( T ), that.Value, true );
  60. }
  61. else
  62. {
  63. return (T)Convert.ChangeType( that.Value, typeof( T ), CultureInfo.InvariantCulture );
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }