using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text.Json; public class JsonConfigManager : IConfigManager { private string? filePath; private Dictionary config = []; private Dictionary? defaultConfig; public T GetValue(string key) { if (config.TryGetValue(key, out object? val)) { if (val is T t) { return t; } else if (val is JsonElement element) { return element.Deserialize() ?? throw new InvalidCastException($"无法将键'{key}'的值转换为类型{typeof(T).Name}"); } } if ( defaultConfig != null && defaultConfig.TryGetValue(key, out object? dval) && dval is T ret) { return ret; } throw new KeyNotFoundException($"Key '{key}' not found in config."); } public bool HasKey(string key) => config.ContainsKey(key); public void SaveToFile() { ArgumentException.ThrowIfNullOrWhiteSpace(filePath); File.WriteAllText(filePath, JsonSerializer.Serialize(config)); } public void LoadFromFile() { ArgumentException.ThrowIfNullOrWhiteSpace(filePath); if (!File.Exists(filePath)) { return; } config = JsonSerializer.Deserialize >(File.ReadAllText(filePath)) ?? []; } public void SetDefault(Dictionary defaultConfig) => this.defaultConfig = defaultConfig; public void SetFilePath(string filePath) => this.filePath = filePath; public void SetValue(string key, [NotNull]object? value) { ArgumentNullException.ThrowIfNull(value); config[key] = value; } }