C#属性。设置。默认

Alex Zhulin

如何确保从中获取价值Properties.Settings.Default例如,当我使用以下代码时:

folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];

并且值SelectedPath不存在,我得到以下异常:

System.dll中发生了System.Configuration.SettingsPropertyNotFoundException”

如何避免这种异常?

迈克·迪内斯库

除非该集合提供了一种检查给定键是否存在的方法,否则您将不得不将代码包装在一个try..catch块中。

 try{
     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
 }catch(System.Configuration.SettingsPropertyNotFoundException)
 {
     folderBrowserDialog1.SelectedPath = "";  // or whatever is appropriate in your case
 }

如果该Default属性实现了IDictionary接口,则可以使用该ContainsKey方法在尝试访问给定键之前测试该键是否存在,如下所示:

 if(Properties.Settings.Default.ContainsKey("SelectedPath"))
 {
     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
 }else{
     folderBrowserDialog1.SelectedPath = ""; // or whatever else is appropriate in your case
 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章