下面的代码演示了如何在.NET Core中使用“内存配置”:
////// 获取格式设置 /// ///public static FormatSettings GetFormatSettings() { // Key使用冒号:分隔路径,实现层级化 Dictionary initialData = new Dictionary { // 时间格式化 ["Format:DateTime:LongDatePattern"] = "dddd, MMMM d, yyyy", ["Format:DateTime:LongTimePattern"] = "h:mm:ss tt", ["Format:DateTime:ShortDatePattern"] = "M/d/yyyy", ["Format:DateTime:ShortTimePattern"] = "h:mm tt", // 金额格式化 ["Format:CurrencyDecimal:Digits"] = "2", ["Format:CurrencyDecimal:Symbol"] = "$", }; var source = new MemoryConfigurationSource { InitialData = initialData }; IConfiguration configuration = new ConfigurationBuilder() .Add(source) .Build().GetSection("Format"); IOptions optionsAccessor = new ServiceCollection() .AddOptions() .Configure (configuration) .BuildServiceProvider() .GetService >(); FormatSettings settings = optionsAccessor.Value; return settings; } /// /// 格式设置类 /// public class FormatSettings { public DateTimeFormatSettings DateTime { get; set; } public CurrencyDecimalFormatSettings CurrencyDecimal { get; set; } } ////// 时间格式化设置 /// public class DateTimeFormatSettings { public string LongDatePattern { get; set; } public string LongTimePattern { get; set; } public string ShortDatePattern { get; set; } public string ShortTimePattern { get; set; } } ////// 货币格式化设置 /// public class CurrencyDecimalFormatSettings { public int Digits { get; set; } public string Symbol { get; set; } }