配置系统
2022/8/4 6:24:08
本文主要是介绍配置系统,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
读取配置文件
{ "persons": [ { "id": 100, "info": { "name": "msy", "age": 18, "skills": [ "CSharp", "Java", "Python" ] } }, { "id": 101, "info": { "name": "wxb", "age": 19, "skills": [ "Javascript", "sql", "ruby" ] } }, { "id": 102, "info": { "name": "zwj", "age": 20, "skills": [ "Go", "Php", "Rust" ] } } ] }
IConfigurationBuilder configBuilder = new ConfigurationBuilder(); // optional=true 找不到配置文件抛出异常 reloadOnChange=true 配置文件被修改,内存也跟着变,false,配置文件被修改,内存不变 configBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configRoot = configBuilder.Build(); /* 读取简单类型,如数字,字符串,GUID,DateTime,这种方式读取的类型都是字符串,需要自己进行类型转换。 */ // 查询第1个人员的名字和年龄 Console.WriteLine(configRoot["persons:0:info:name"]); Console.WriteLine(int.Parse(configRoot.GetRequiredSection("persons:0:info")["age"])); Console.WriteLine(configRoot.GetSection("persons:0:info:name").Value); Console.WriteLine(configRoot.GetRequiredSection("persons:0:info").GetValue<int>("age")); // 查询所有的人员掌握的技能 IEnumerable<IConfigurationSection> sections = configRoot.GetSection("persons").GetChildren(); foreach (IConfigurationSection section in sections) { IEnumerable<IConfigurationSection> skills = section.GetSection("info:skills").GetChildren(); foreach (IConfigurationSection skill in skills) { Console.WriteLine(skill.Value); Console.WriteLine(skill.Path); Console.WriteLine(skill.Key); } } /* 读取复杂类型,映射到类 */ // 查询第1个人员的名字和年龄 ObjectPersonModel model = configRoot.GetSection("persons:0:info").Get<ObjectPersonModel>(options => options.ErrorOnUnknownConfiguration = true); Console.WriteLine(model.name); Console.WriteLine(model.age); Console.WriteLine(string.Join(",", model.skills)); var ret = configRoot.GetSection("persons").Get<IList<RelationalPersonModel>>(); Console.WriteLine(ret[0].id);
这篇关于配置系统的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?