配置系统
作者:互联网
读取配置文件
{
"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);
标签:info,Console,skills,配置,系统,persons,WriteLine,configRoot 来源: https://www.cnblogs.com/LiuwayLi/p/16549286.html