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

前端 未结 5 1901
忘了有多久
忘了有多久 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 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)

提交回复
热议问题