4

ASP.NET

对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,将返回该值。我正要创建一个类来管理它,但我想这个功能可能已经在 .NET Framework 的某个地方了?

.NET 中是否有一个 NameValueCollection/Hash/etc-type 类可以让我指定一个键和一个备用/默认值——并返回键的值或指定的值?

如果有,我可以在调用它之前将 appSettings 放入该类型的对象中(从不同的地方)。

4

5 回答 5

3

这就是我所做的。

WebConfigurationManager.AppSettings["MyValue"] ?? "SomeDefault")

对于布尔值和其他非字符串类型...

bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")
于 2017-08-30T21:36:26.343 回答
2

我不相信 .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;
        }
    }
}

您可能可以摆脱strings 而不是保持通用。

如果可以的话,还有来自 Silverlight 和 WPF 世界的DependencyObject 。

当然,最简单的方法是这样的NameValueCollection

string value = string.IsNullOrEmpty(appSettings[key]) 
    ? defaultValue 
    : appSettings[key];

key可以null在字符串索引器上。但我知道在多个地方这样做很痛苦。

于 2010-09-21T19:30:05.853 回答
1

您可以制作自定义配置部分并使用 DefaultValue 属性提供默认值。此处提供了相关说明。

于 2010-09-21T18:11:30.633 回答
0

我认为 C:\%WIN%\Microsoft.NET 下的 machine.config 会这样做。将键添加到该文件作为默认值。

http://msdn.microsoft.com/en-us/library/ms228154.aspx

于 2010-09-21T18:03:00.403 回答
0

您可以围绕 ConfigurationManager 构建逻辑,以获得一种类型化的方式来检索您的应用设置值。在这里使用 TypeDescriptor 来转换值。

/// <summary>
/// Utility methods for ConfigurationManager
/// </summary>
public static class ConfigurationManagerWrapper
{
    /// <summary>
    /// Use this extension method to get a strongly typed app setting from the configuration file.
    /// Returns app setting in configuration file if key found and tries to convert the value to a specified type. In case this fails, the fallback value
    /// or if NOT specified - default value - of the app setting is returned
    /// </summary>
    public static T GetAppsetting<T>(string appsettingKey, T fallback = default(T))
    {
        string val = ConfigurationManager.AppSettings[appsettingKey] ?? "";
        if (!string.IsNullOrEmpty(val))
        {
            try
            {
                Type typeDefault = typeof(T);
                var converter = TypeDescriptor.GetConverter(typeof(T));
                return converter.CanConvertFrom(typeof(string)) ? (T)converter.ConvertFrom(val) : fallback;
            }
            catch (Exception err)
            {
                Console.WriteLine(err); //Swallow exception
                return fallback;
            }
        }
        return fallback;
    }
}
于 2019-02-20T16:14:27.347 回答