这个组件的主要作用是将设置(Setttings)的内容,根据键值关系填充到已经存在的实体或静态类中
先来一个最简单的例子
有一个叫tests
的项目,app.config
的配置文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="tests.datetime" value="2017-1-1 0:0:0"/>
<add key="tests.url" value="//baidu.com"/>
<add key="tests.maxlength" value="9999.99"/>
<add key="tests.minlength" value="0.01"/>
<add key="tests.delay" value="1000"/>
<add key="tests.enable" value="true"/>
</appSettings>
</configuration>
* 在使用中我比较喜欢在设置前加上项目的前缀或命名空间, 以便区分不同项目间的同名设置项
过去在项目中使用配置文件一般是
static void Main(string[] args)
{
var timeValue = System.Configuration.ConfigurationManager.AppSettings["tests.datetime"];
if(!DateTime.TryParse(timeValue, out var time))
{
time = new DateTime(1970, 1, 1);
}
Console.WriteLine(time);
}
不仅臃肿,而且不易阅读和维护
好一点的做法是
static class Settings
{
static Settings()
{
var settings = System.Configuration.ConfigurationManager.AppSettings;
if (DateTime.TryParse(settings["tests.datetime"], out var time))
{
DateTime = new DateTime(1970, 1, 1);
}
if (Uri.TryCreate(settings["tests.url"],UriKind.RelativeOrAbsolute,out var url))
{
Url = url;
}
if (float.TryParse(settings["tests.maxlength"], out var maxlength))
{
MaxLength = maxlength;
}
if (float.TryParse(settings["tests.minlength"], out var minlength))
{
MinLength = minlength;
}
if (int.TryParse(settings["tests.delay"], out var delay))
{
Delay = delay;
}
if (bool.TryParse(settings["tests.enable"], out var enable))
{
Enable = enable;
}
}
public static DateTime DateTime { get; private set; } = new DateTime(1970, 1, 1);
public static Uri Url { get; private set; }
public static float MaxLength { get; private set; }
public static float MinLength { get; private set; }
public static int Delay { get; private set; }
public static bool Enable { get; private set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Settings.DateTime);
Console.WriteLine(Settings.Url);
Console.WriteLine(Settings.MaxLength);
Console.WriteLine(Settings.MinLength);
Console.WriteLine(Settings.Delay);
Console.WriteLine(Settings.Enable);
}
}
这例子中是6个设置,而实际如果有10个甚至20个设置,那将变得非常枯燥
所以有了 SettingsFetcher
[SettingsGroupName("tests")]
static class Settings
{
static Settings() => SettingsFetcher.Fill(typeof(Settings), false);
public static DateTime DateTime { get; private set; } = new DateTime(1970, 1, 1);
public static Uri Url { get; private set; }
public static float MaxLength { get; private set; }
public static float MinLength { get; private set; }
public static int Delay { get; private set; }
public static bool Enable { get; private set; }
}
使用 [SettingsGroupName("tests")]
这个特性来设置前缀,名称直接根据属性名称匹配
更多的用法可以参考