我有以下内容:
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);
}
}
答案 0 :(得分:19)
如果您使用的是SettingsPropertyCollection
,则必须循环并检查自己存在哪些设置,因为它没有任何Contains方法。
private bool DoesSettingExist(string settingName)
{
return Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(prop => prop.Name == settingName);
}
答案 1 :(得分:6)
根据CommomSettings.Default
的类型,简单的空检查应该没问题:
if(setting != null)
DoSomethingElse(setting);
如果要在尝试检索设置之前检查,则需要发布CommonSettings.Default类型。它看起来像一个词典,所以你可以逃脱:
if(CommonSettings.Default.ContainsKey(str))
{
DoSomethingElse(CommonSettings.Default[str]);
}
答案 2 :(得分:6)
try
{
var x = Settings.Default[bonusMalusTypeKey]);
}
catch (SettingsPropertyNotFoundException ex)
{
// Ignore this exception (return default value that was set)
}
答案 3 :(得分:5)
这就是你如何处理它:
if(CommonSettings.Default.Properties[str] != null)
{
//Hooray, we found it!
}
else
{
//This is a 'no go'
}
答案 4 :(得分: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);
}
}
这将确保设置存在 - 您可以更进一步尝试捕获确切的例外 - 例如catch(IndexOutOfBoundsException ex)