lan*_*nce 5 c# asp.net appsettings namevaluecollection fallbackvalue
网络平台
对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,则将返回该值。我本来打算创建一个类来管理它,但我想这个功能可能已经在 .NET Framework 中的某个地方了?
.NET 中是否有一个 NameValueCollection/Hash/etc 类型的类,可以让我指定一个键和一个后备/默认值——并返回键的值或指定的值?
如果有,我可以在调用它之前(从不同的地方)将 appSettings 放入该类型的对象中。
小智 5
ASP.NET 的 ConfigurationManager 提供了该功能。您可以使用 或来将配置节(通过 检索.GetSection("MySection"))绑定到对象。这还有一个好处,它可以为您进行转换(请参阅示例中的整数)。.Get<MySectionType>().Bind(mySectionTypeInstance)
应用程序设置.json
{
"MySection": {
"DefinedString": "yay, I'm defined",
"DefinedInteger": 1337
}
}
Run Code Online (Sandbox Code Playgroud)
MySection.cs
// could also be a struct or readonly struct
public class MySectionType
{
public string DefinedString { get; init; } = "default string";
public int DefinedInteger { get; init; } = -1;
public string OtherString { get; init; } = "default string";
public int OtherInteger { get; init; } = -1;
public override string ToString() =>
$"defined string : \"{DefinedString}\"\n" +
$"defined integer: {DefinedInteger}\n" +
$"undefined string : \"{OtherString}\"\n" +
$"undefined integer: {OtherInteger}";
}
Run Code Online (Sandbox Code Playgroud)
程序.cs
ConfigurationManager configuration = GetYourConfigurationManagerHere();
// either
var mySection = configuration.GetSection("MySection").Get<MySectionType>();
// or
var mySection = new MySectionType();
configuration.GetSection("MySection").Bind(mySection);
Console.WriteLine(mySection);
// output:
// defined string : "yay, I'm defined"
// defined integer: 1337
// undefined string : "default string"
// undefined integer: -1
Run Code Online (Sandbox Code Playgroud)
我不相信 .NET 中内置了任何东西可以提供您正在寻找的功能。
您可以创建一个基于该类的重载,并为默认值Dictionary<TKey, TValue>提供附加参数,例如:TryGetValue
public class MyAppSettings<TKey, TValue> : Dictionary<TKey, TValue>
{
public void TryGetValue(TKey key, out TValue value, TValue defaultValue)
{
if (!this.TryGetValue(key, out value))
{
value = defaultValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可能可以摆脱strings 而不是保持通用。
如果可以的话,还有来自 Silverlight 和 WPF 世界的DependencyObject 。
当然,最简单的方法是这样的NameValueCollection:
string value = string.IsNullOrEmpty(appSettings[key])
? defaultValue
: appSettings[key];
Run Code Online (Sandbox Code Playgroud)
key可以null在字符串索引器上。但我知道在多个地方这样做很痛苦。