Files
chess_game/Scripts/Utilities/JsonConfig.cs

53 lines
1.8 KiB
C#

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<string, object> config = [];
private Dictionary<string, object>? defaultConfig;
public T GetValue<T>(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<T>() ??
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
<Dictionary<string, object>>(File.ReadAllText(filePath)) ?? [];
}
public void SetDefault(Dictionary<string, object> 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;
}
}