From 5cd01a637593ca49c10ed352f18574c818fb0066 Mon Sep 17 00:00:00 2001
From: Jack <3486688394@qq.com>
Date: Tue, 21 Jan 2025 19:01:55 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E9=85=8D=E7=BD=AE?=
=?UTF-8?q?=E6=96=87=E4=BB=B6=E8=AF=BB=E5=86=99=E9=80=BB=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 修改配置数据初始化方式,提高代码可读性- 完善 Get 方法,增加默认值设置和类型转换逻辑- 重构 Set 方法,优化配置数据更新流程
- 更新解决方案设置
---
JackCraft.Config.sln.DotSettings.user | 5 ++++-
JackCraft.Config/Config.cs | 31 ++++++++++++++++++++-------
2 files changed, 27 insertions(+), 9 deletions(-)
diff --git a/JackCraft.Config.sln.DotSettings.user b/JackCraft.Config.sln.DotSettings.user
index c9fbfed..5e14006 100644
--- a/JackCraft.Config.sln.DotSettings.user
+++ b/JackCraft.Config.sln.DotSettings.user
@@ -1,4 +1,7 @@
+ ForceIncluded
ForceIncluded
ForceIncluded
- ForceIncluded
\ No newline at end of file
+ ForceIncluded
+ ForceIncluded
+ ForceIncluded
\ No newline at end of file
diff --git a/JackCraft.Config/Config.cs b/JackCraft.Config/Config.cs
index ec5e5cc..4dffce5 100644
--- a/JackCraft.Config/Config.cs
+++ b/JackCraft.Config/Config.cs
@@ -8,7 +8,7 @@ public class Config
private readonly FileInfo _configFile;
public readonly string ConfigFileName;
public readonly string ConfigFilePath;
- private Dictionary _configData = null!;
+ private Dictionary _configData = new();
public Config(FileInfo configFile)
{
@@ -46,7 +46,12 @@ public class Config
var currentData = _configData;
for (var i = 0; i < keys.Length - 1; i++)
{
- if (!currentData.TryGetValue(keys[i], out var tValue)) return defaultValue;
+ if (!currentData.TryGetValue(keys[i], out var tValue))
+ {
+ Set(key, defaultValue);
+ return defaultValue;
+ }
+
switch (tValue)
{
case JObject jObject:
@@ -56,12 +61,14 @@ public class Config
currentData = nestedDict;
break;
default:
+ Set(key, defaultValue);
return defaultValue;
}
}
if (currentData.TryGetValue(keys[^1], out var result) && result is T typedResult) return typedResult;
+ Set(key, defaultValue);
return defaultValue;
}
@@ -70,19 +77,27 @@ public class Config
LoadConfigData();
var keys = key.Split('.');
var currentData = _configData;
+
for (var i = 0; i < keys.Length - 1; i++)
{
- if (!currentData.TryGetValue(keys[i], out var tValue) ||
- tValue is not Dictionary nestedDict)
+ var currentKey = keys[i];
+
+ if (!currentData.TryGetValue(currentKey, out var tValue))
{
- nestedDict = new Dictionary();
- currentData[keys[i]] = nestedDict;
+ tValue = new Dictionary();
+ currentData[currentKey] = tValue;
}
- currentData = nestedDict;
+ if (tValue is JObject jObject)
+ currentData[currentKey] =
+ jObject.ToObject>() ?? new Dictionary();
+
+ currentData = (Dictionary)currentData[currentKey];
}
- currentData[keys[^1]] = (object?)value ?? string.Empty;
+ var finalKey = keys[^1];
+ currentData[finalKey] = value!;
+
var json = JsonConvert.SerializeObject(_configData, Formatting.Indented);
File.WriteAllText(_configFile.FullName, json);
}