C#: 如何确保在尝试使用来自另一个程序集的设置变量之前该变量存在?

17

我有以下内容:

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);
    }
}

https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx - CAD bloke
5个回答

30

如果您正在使用 SettingsPropertyCollection,似乎需要自己循环并检查哪些设置存在,因为它没有任何包含方法。

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

2
谢谢salle55,做得很好。 对于那些没有使用System.Configuration的人,请在SettingsProperty前添加前缀System.Configuration。 - gg89

6
根据 CommomSettings.Default 的类型不同,一个简单的空检查应该就可以了:
if(setting != null)
    DoSomethingElse(setting);

如果您想在尝试检索设置之前进行检查,则需要发布CommonSettings.Default的类型。它看起来像一个字典,因此您可能可以使用以下方法:

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

我认为他更想知道如何确保该设置存在,而不仅仅是检查它是否存在。 - Uwe Keim
1
@Uwe - 你可能是对的。我无法从OP问题中的措辞中判断出来。我也为那种情况添加了一些内容。 - Justin Niessner
1
然而,Settings.settings文件是如何构建的...我认为它不是字典类型,因为'intellisense'中没有CommonSettings.Default.ContainsKey(...) - michael
2
这不适用于Properties.Settings.Default。@Salle55提供了一个好的解决方案,下面可以使用Properties.Settings.Default。 - Paul Stark
对于我来说:CommonSettings.Default.Context.ContainsKey(str)(VS 2019,.NET4.5) - David Silva-Barrera

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

一些描述会很有用! - Parris

5
这是处理它的方法:
if(CommonSettings.Default.Properties[str] != null)
{
    //Hooray, we found it!
}
else
{
    //This is a 'no go'
}

1
即使您之前没有设置,此条件仍将为真。我认为OP想知道这些设置以前是否已设置。 - Javidan

0
你可以这样做:
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);
    }
}

这将确保设置存在 - 你可以再进一步尝试并捕获确切的异常 - 比如捕获(IndexOutOfBoundsException ex)。

刚看到你的更新,Justin - 你的解决方案看起来更加简洁 :) - GaryT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接