public class FormSettings
{
public string Title { get; set; }
public bool FullScreen { get; set; }
}
public class Role
{
public bool IsAdmin { get; set; }
}
public class Logging
{
public bool Use { get; set; }
public LoggingDestination Destination { get; set; }
public string LogFileName { get; set; }
}
public enum LoggingDestination
{
DebugWindow,
LogFile,
None
}
从appsettings.json读取设置的类
public class AppSettings
{
private static ConfigurationBuilder _configBuilder;
public static Logging GetLogOptions()
{
Build();
return InitOptions<Logging>("LogOptions");
}
public static Role Role()
{
Build();
return InitOptions<Role>("Role");
}
public static FormSettings Settings()
{
Build();
return InitOptions<FormSettings>("FormSettings");
}
private static IConfigurationRoot Build()
{
if (_configBuilder is not null) return _configBuilder.Build();
_configBuilder = new ConfigurationBuilder();
_configBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true);
return _configBuilder.Build();
}
public static T InitOptions<T>(string section) where T : new()
=> Build().GetSection(section).Get<T>();
}
用途
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Text = AppSettings.Role().IsAdmin
? AppSettings.Settings().Title + " (Admin)"
: AppSettings.Settings().Title ;
}
private void GetLogInfoButton_Click(object sender, EventArgs e)
{
if (AppSettings.GetLogOptions().Use && AppSettings.GetLogOptions().Destination == LoggingDestination.LogFile)
{
MessageBox.Show($"{AppSettings.GetLogOptions().LogFileName}");
}
}
}
1条答案
按热度按时间lb3vh1jj1#
假设这是针对
appsettings.json
的,使用以下文件使用以下类从
appsettings.json
获取值从
appsettings.json
读取设置的类用途
NuGet软件包