TypeConversionDemo.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Apq.Cfg.Samples.Models;
  2. namespace Apq.Cfg.Samples.Demos;
  3. /// <summary>
  4. /// 示例 5: 类型转换
  5. /// </summary>
  6. public static class TypeConversionDemo
  7. {
  8. public static async Task RunAsync(string baseDir)
  9. {
  10. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  11. Console.WriteLine("示例 5: 类型转换");
  12. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  13. var configPath = Path.Combine(baseDir, "types-demo.json");
  14. File.WriteAllText(configPath, """
  15. {
  16. "Types": {
  17. "IntValue": "42",
  18. "LongValue": "9223372036854775807",
  19. "DoubleValue": "3.14159",
  20. "DecimalValue": "123.456",
  21. "BoolTrue": "true",
  22. "BoolFalse": "false",
  23. "DateValue": "2024-12-25",
  24. "GuidValue": "550e8400-e29b-41d4-a716-446655440000",
  25. "EnumValue": "Warning"
  26. }
  27. }
  28. """);
  29. using var cfg = new CfgBuilder()
  30. .AddJson(configPath, level: 0, writeable: false)
  31. .Build();
  32. Console.WriteLine("5.1 各种类型转换:");
  33. Console.WriteLine($" int: {cfg.Get<int>("Types:IntValue")}");
  34. Console.WriteLine($" long: {cfg.Get<long>("Types:LongValue")}");
  35. Console.WriteLine($" double: {cfg.Get<double>("Types:DoubleValue")}");
  36. Console.WriteLine($" decimal: {cfg.Get<decimal>("Types:DecimalValue")}");
  37. Console.WriteLine($" bool (true): {cfg.Get<bool>("Types:BoolTrue")}");
  38. Console.WriteLine($" bool (false): {cfg.Get<bool>("Types:BoolFalse")}");
  39. Console.WriteLine($" DateTime: {cfg.Get<DateTime>("Types:DateValue"):yyyy-MM-dd}");
  40. Console.WriteLine($" Guid: {cfg.Get<Guid>("Types:GuidValue")}");
  41. Console.WriteLine($" Enum: {cfg.Get<LogLevel>("Types:EnumValue")}");
  42. Console.WriteLine("\n5.2 可空类型与默认值:");
  43. Console.WriteLine($" 不存在的键 (int?): {cfg.Get<int?>("Types:NotExist") ?? -1}");
  44. Console.WriteLine($" 不存在的键 (string): {cfg.Get("Types:NotExist") ?? "(null)"}");
  45. File.Delete(configPath);
  46. Console.WriteLine("\n[示例 5 完成]\n");
  47. await Task.CompletedTask;
  48. }
  49. }