BatchOperationsDemo.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. namespace Apq.Cfg.Samples.Demos;
  2. /// <summary>
  3. /// 示例 4: 批量操作 - GetMany / SetMany
  4. /// </summary>
  5. public static class BatchOperationsDemo
  6. {
  7. public static async Task RunAsync(string baseDir)
  8. {
  9. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  10. Console.WriteLine("示例 4: 批量操作 - GetMany / SetMany");
  11. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  12. var configPath = Path.Combine(baseDir, "batch-demo.json");
  13. File.WriteAllText(configPath, """
  14. {
  15. "Settings": {
  16. "Theme": "dark",
  17. "Language": "zh-CN",
  18. "FontSize": "14",
  19. "AutoSave": "true"
  20. }
  21. }
  22. """);
  23. using var cfg = new CfgBuilder()
  24. .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
  25. .Build();
  26. // 批量获取
  27. Console.WriteLine("4.1 批量获取 (GetMany):");
  28. var keys = new[] { "Settings:Theme", "Settings:Language", "Settings:FontSize" };
  29. var values = cfg.GetMany(keys);
  30. foreach (var kv in values)
  31. {
  32. Console.WriteLine($" {kv.Key} = {kv.Value}");
  33. }
  34. // 批量获取并转换类型
  35. Console.WriteLine("\n4.2 批量获取并转换类型 (GetMany<T>):");
  36. var intKeys = new[] { "Settings:FontSize" };
  37. var intValues = cfg.GetMany<int>(intKeys);
  38. foreach (var kv in intValues)
  39. {
  40. Console.WriteLine($" {kv.Key} = {kv.Value} (int)");
  41. }
  42. // 批量设置
  43. Console.WriteLine("\n4.3 批量设置 (SetMany):");
  44. var newValues = new Dictionary<string, string?>
  45. {
  46. ["Settings:Theme"] = "light",
  47. ["Settings:FontSize"] = "16",
  48. ["Settings:NewOption"] = "enabled"
  49. };
  50. cfg.SetMany(newValues);
  51. await cfg.SaveAsync();
  52. Console.WriteLine(" 批量设置后的值:");
  53. var updatedValues = cfg.GetMany(new[] { "Settings:Theme", "Settings:FontSize", "Settings:NewOption" });
  54. foreach (var kv in updatedValues)
  55. {
  56. Console.WriteLine($" {kv.Key} = {kv.Value}");
  57. }
  58. File.Delete(configPath);
  59. Console.WriteLine("\n[示例 4 完成]\n");
  60. }
  61. }