using System; using System.Collections.Generic; public class ConfigCache { // 单例实例 private static ConfigCache _instance; public static ConfigCache Instance { get { _instance ??= new ConfigCache(); return _instance; } } // 私有构造函数,防止外部实例化 private ConfigCache() { _configDictionary = new Dictionary(); } // 用于存储配置的字典 private readonly Dictionary _configDictionary; /// /// 设置配置项 /// /// 配置的键 /// 配置的值 public void SetConfig(string key, string value) { if (string.IsNullOrEmpty(key)) { Console.WriteLine("键不能为空!"); return; } if (_configDictionary.ContainsKey(key)) { _configDictionary[key] = value; // 如果键已存在,更新值 Console.WriteLine($"配置已更新:{key} = {value}"); } else { _configDictionary.Add(key, value); // 如果键不存在,添加新项 Console.WriteLine($"配置已添加:{key} = {value}"); } } /// /// 获取配置项 /// /// 配置的键 /// 配置的值,如果键不存在返回 null public string GetConfig(string key) { if (string.IsNullOrEmpty(key)) { Console.WriteLine("键不能为空!"); return null; } if (_configDictionary.TryGetValue(key, out string value)) { Console.WriteLine($"读取到配置:{key} = {value}"); return value; } else { Console.WriteLine($"配置项不存在:{key}"); return null; } } /// /// 删除配置项 /// /// 配置的键 public void RemoveConfig(string key) { if (string.IsNullOrEmpty(key)) { Console.WriteLine("键不能为空!"); return; } if (_configDictionary.Remove(key)) { Console.WriteLine($"配置已删除:{key}"); } else { Console.WriteLine($"配置项不存在,无法删除:{key}"); } } /// /// 清空所有配置 /// public void ClearConfigs() { _configDictionary.Clear(); Console.WriteLine("所有配置已清空!"); } }