[英]C# Properties.Settings.Default
如何確保從Properties.Settings.Default
檢索值存在? 例如,當我使用此代碼時:
folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
並且值SelectedPath
不存在,我得到以下異常:
System.Configuration.SettingsPropertyNotFoundException' 發生在 System.dll 中
我怎樣才能避免這個異常?
這是一種檢查密鑰是否存在的方法:
public static bool PropertiesHasKey(string key)
{
foreach (SettingsProperty sp in Properties.Settings.Default.Properties)
{
if (sp.Name == key)
{
return true;
}
}
return false;
}
除非該集合提供了檢查給定鍵是否存在的方法,否則您必須將代碼包裝在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
}
試試這個:(我們的朋友“邁克·迪內斯庫”提到了沒有詳細信息 - 編輯:他現在提供了詳細信息)
try
{
folderBrowserDialog1.SelectedPath =
(string)Properties.Settings.Default["SelectedPath"]
}
catch(System.Configuration.SettingsPropertyNotFoundException e)
{
MessageBox.Show(e.Message); // or anything you want
}
catch(Exception e)
{
//if any exception but above one occurs this part will execute
}
我希望這個解決方案能解決你的問題:)
編輯:或者不使用 try catch :
if(!String.IsNullOrEmpty((string)Properties.Settings.Default["SelectedPath"]))
{
folderBrowserDialog1.SelectedPath =
(string)Properties.Settings.Default["SelectedPath"]
}
您可以為變量設置默認null
值。 將此代碼添加到Settings.Designer.cs
文件:
[UserScopedSetting]
[DebuggerNonUserCode]
[DefaultSettingValue(null)] // <-- set default value
public string test1
{
get
{
return (string)this[nameof(test1)];
}
set
{
this[nameof(test1)] = (object)value;
}
}
然后檢查:
if (Properties.Settings.Default.test1 != null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.