下面的代碼演示瞭如何在.NET Core中使用「內存配置」:git
/// <summary> /// 獲取格式設置 /// </summary> /// <returns></returns> public static FormatSettings GetFormatSettings() { // Key使用冒號:分隔路徑,實現層級化 Dictionary<string, string> initialData = new Dictionary<string, string> { // 時間格式化 ["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<FormatSettings> optionsAccessor = new ServiceCollection() .AddOptions() .Configure<FormatSettings>(configuration) .BuildServiceProvider() .GetService<IOptions<FormatSettings>>(); FormatSettings settings = optionsAccessor.Value; return settings; } /// <summary> /// 格式設置類 /// </summary> public class FormatSettings { public DateTimeFormatSettings DateTime { get; set; } public CurrencyDecimalFormatSettings CurrencyDecimal { get; set; } } /// <summary> /// 時間格式化設置 /// </summary> public class DateTimeFormatSettings { public string LongDatePattern { get; set; } public string LongTimePattern { get; set; } public string ShortDatePattern { get; set; } public string ShortTimePattern { get; set; } } /// <summary> /// 貨幣格式化設置 /// </summary> public class CurrencyDecimalFormatSettings { public int Digits { get; set; } public string Symbol { get; set; } }