using System; using System.Application.Serialization; using System.Application.Services; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Text; namespace System.Application.Models.Settings { public abstract class SettingsHost { private static readonly Dictionary instances = new(); private readonly Dictionary cachedProperties = new(); protected virtual string CategoryName => this.GetType().Name; protected SettingsHost() { instances[this.GetType()] = this; } /// /// 请参阅 缓存在当前实例中获取 /// 如果没有缓存,根据创建它 /// /// protected SerializableProperty Cache(Func> create, [CallerMemberName] string propertyName = "") { var key = this.CategoryName + "." + propertyName; if (this.cachedProperties.TryGetValue(key, out object obj) && obj is SerializableProperty property1) return property1; var property = create(key); this.cachedProperties[key] = property; return property; } #region Load / Save public static void Load() { try { Providers.Local.Load(); } catch (Exception ex) { Log.Error(nameof(SettingsHost), "Config Load", ex); File.Delete(Providers.LocalFilePath); Providers.Local.Load(); } } public static void Save() { try { Providers.Local.Save(); } catch (Exception ex) { Log.Error(nameof(SettingsHost), "Config Save", ex); throw; } } #endregion /// /// 获取类型的配置对象的唯一实例。 /// public static T Instance() where T : SettingsHost, new() { return instances.TryGetValue(typeof(T), out SettingsHost host) ? (T)host : new T(); } } public class Providers { public static string LocalFilePath => Path.Combine(IOPath.AppDataDirectory, IConfigFileService.ConfigFileName); public static ISerializationProvider Local { get; } = new FileSettingsProvider(LocalFilePath); } }