C#: How to make sure a settings variable exists be

2019-03-25 17:35发布

问题:

I have the following:

using CommonSettings = MyProject.Commons.Settings;

public class Foo
{
    public static void DoSomething(string str)
    {
        //How do I make sure that the setting exists first?
        object setting = CommonSettings.Default[str];

        DoSomethingElse(setting);
    }
}

回答1:

Depending on what type CommomSettings.Default is, a simple null check should be fine:

if(setting != null)
    DoSomethingElse(setting);

If you want to check BEFORE trying to retrieve the setting, you need to post the Type of CommonSettings.Default. It looks like a Dictionary so you might be able to get away with:

if(CommonSettings.Default.ContainsKey(str))
{
    DoSomethingElse(CommonSettings.Default[str]);
}


回答2:

If you are using a SettingsPropertyCollection you have to loop and check which settings exists yourself it seems, since it doesn't have any Contains-method.

private bool DoesSettingExist(string settingName)
{
   return Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(prop => prop.Name == settingName);
}


回答3:

try
{
    var x = Settings.Default[bonusMalusTypeKey]);
}
catch (SettingsPropertyNotFoundException ex)
{
    // Ignore this exception (return default value that was set)
}


回答4:

This is how you deal with it:

if(CommonSettings.Default.Properties[str] != null)
{
    //Hooray, we found it!
}
else
{
    //This is a 'no go'
}


回答5:

You could do the following:

public static void DoSomething(string str)
{
    object setting = null;

    Try
    {
        setting = CommonSettings.Default[str];
    }
    catch(Exception ex)
    {
        Console.out.write(ex.Message);
    }

    if(setting != null)
    {
        DoSomethingElse(setting);
    }
}

This would ensure the setting exists - you could go a bit further and try and catch the exact excetion - e.g catch(IndexOutOfBoundsException ex)