Fallback / Default AppSettings?

ASP.NET

For each appSetting used, I want to specify a value that will be returned if the specified key is not found in appSettings. I was going to create a class to manage this, but I think that this functionality probably already exists in the .NET Framework somewhere?

In .NET there is a class NameValueCollection / Hash / etc-type, which will allow me to specify the key and the value fallback / default - and return either the key value or the specified value?

If there is, I can put appSettings in an object of this type before calling it (from different places).

+3
source share
4 answers

, .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;
        }
    }
}

, string .

DependencyObject Silverlight WPF, .

, - - NameValueCollection:

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

key null . , , .

+2

, .

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

...

bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")
+2

You can create a custom configuration section and provide default values ​​using the DefaultValue attribute. Instructions for this are available here .

+1
source

I think machine.config in C: \% WIN% \ Microsoft.NET will do this. Add keys to this file as default values.

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

0
source

Source: https://habr.com/ru/post/1765862/


All Articles