feat(config): 添加自定义读取和保存方法支持
- 引入 ConfigReader 和 ConfigWriter 委托类型定义 - 在 Config 构造函数中添加自定义读取和保存方法参数 - 实现 ReadConfigFile 和 WriteConfigFile 辅助方法 - 修改文件操作使用自定义方法或默认方法 - 更新测试程序添加多种自定义方法使用示例 - 在文档中添加自定义方法使用的代码示例
This commit is contained in:
33
Readme.MD
33
Readme.MD
@@ -13,6 +13,39 @@
|
||||
var config = new Config(new FileInfo("./config.json"));
|
||||
```
|
||||
|
||||
```csharp
|
||||
// 定义自定义读取方法
|
||||
Config.ConfigReader customReader = (filePath) => {
|
||||
Console.WriteLine($"正在读取文件: {filePath}");
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
var content = File.ReadAllText(filePath);
|
||||
Console.WriteLine($"文件内容: {content}");
|
||||
return content;
|
||||
}
|
||||
return "{}";
|
||||
};
|
||||
|
||||
// 定义自定义保存方法
|
||||
Config.ConfigWriter customWriter = (filePath, content) => {
|
||||
Console.WriteLine($"正在保存到文件: {filePath}");
|
||||
|
||||
// 创建备份
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
var backupPath = filePath + ".backup";
|
||||
File.Copy(filePath, backupPath, true);
|
||||
Console.WriteLine($"已创建备份: {backupPath}");
|
||||
}
|
||||
|
||||
File.WriteAllText(filePath, content);
|
||||
Console.WriteLine("文件保存完成");
|
||||
};
|
||||
|
||||
// 使用自定义方法创建 Config 实例
|
||||
var config = new Config(new FileInfo("./config.json"), customReader, customWriter);
|
||||
```
|
||||
|
||||
### 读取键值
|
||||
|
||||
> 若键不存在则返回默认值,并且同时也会写入键值(若没有提供默认值则写入空)
|
||||
|
||||
Reference in New Issue
Block a user