Interface ICfgSection
配置节接口,表示配置的一个子节
public interface ICfgSection
Properties
this[string]
通过索引器获取或设置配置值(相对于此节的键)
string? this[string key] { get; set; }
Parameters
keystring相对于此节的键名
Property Value
- string
配置值,不存在时返回null
Examples
var dbSection = cfg.GetSection("Database");
// 读取配置
var host = dbSection["Host"]; // 等同于 cfg["Database:Host"]
// 写入配置
dbSection["Host"] = "localhost"; // 等同于 cfg["Database:Host"] = "localhost"
Path
获取此节的路径前缀
string Path { get; }
Property Value
Examples
var dbSection = cfg.GetSection("Database");
Console.WriteLine(dbSection.Path); // 输出: Database
Methods
Exists(string)
检查配置键是否存在
bool Exists(string key)
Parameters
keystring相对于此节的键名
Returns
- bool
存在返回true,否则返回false
Examples
var dbSection = cfg.GetSection("Database");
if (dbSection.Exists("ConnectionString"))
{
// 处理连接字符串
}
GetChildKeys()
获取所有子节的键名
IEnumerable<string> GetChildKeys()
Returns
- IEnumerable<string>
子节键名集合
Examples
var dbSection = cfg.GetSection("Database");
foreach (var key in dbSection.GetChildKeys())
{
Console.WriteLine($"{key}: {dbSection.Get(key)}");
}
GetSection(string)
获取子节
ICfgSection GetSection(string key)
Parameters
keystring子节键名
Returns
- ICfgSection
子节对象
Examples
var dbSection = cfg.GetSection("Database");
var connSection = dbSection.GetSection("Connection"); // 等同于 cfg.GetSection("Database:Connection")
GetValue<T>(string)
获取配置值并转换为指定类型
T? GetValue<T>(string key)
Parameters
keystring相对于此节的键名
Returns
- T
转换后的配置值,不存在或转换失败时返回默认值
Type Parameters
T目标类型
Examples
var dbSection = cfg.GetSection("Database");
var port = dbSection.GetValue<int>("Port"); // 等同于 cfg.GetValue<int>("Database:Port")
Remove(string, int?)
移除配置键
void Remove(string key, int? targetLevel = null)
Parameters
Examples
var dbSection = cfg.GetSection("Database");
dbSection.Remove("OldSetting"); // 等同于 cfg.Remove("Database:OldSetting")
SetValue(string, string?, int?)
设置配置值
void SetValue(string key, string? value, int? targetLevel = null)
Parameters
Examples
var dbSection = cfg.GetSection("Database");
dbSection.SetValue("Timeout", "60"); // 等同于 cfg.SetValue("Database:Timeout", "60")