C#: How to make sure a settings variable exists before attempting to use it from another assembly?

前端 未结 5 1902
忘了有多久
忘了有多久 2021-02-07 11:10

I have the following:

using CommonSettings = MyProject.Commons.Settings;

public class Foo
{
    public static void DoSomething(string str)
    {
        //How d         


        
相关标签:
5条回答
  • 2021-02-07 11:44
    try
    {
        var x = Settings.Default[bonusMalusTypeKey]);
    }
    catch (SettingsPropertyNotFoundException ex)
    {
        // Ignore this exception (return default value that was set)
    }
    
    0 讨论(0)
  • 2021-02-07 11:49

    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]);
    }
    
    0 讨论(0)
  • 2021-02-07 11:55

    This is how you deal with it:

    if(CommonSettings.Default.Properties[str] != null)
    {
        //Hooray, we found it!
    }
    else
    {
        //This is a 'no go'
    }
    
    0 讨论(0)
  • 2021-02-07 12:00

    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);
    }
    
    0 讨论(0)
  • 2021-02-07 12:01

    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)

    0 讨论(0)
提交回复
热议问题