僞代碼:c#如何將var與另一個var連接以指向應用程序SettingsName?
using wLog.Properties;
var sName = frmControlProp[cn].SettingName;
var pSettings = Properties.Settings.Default + sName;
SNAME值等於,例如,密碼。我想pSettings等於Properties.Settings.Default.Password
我該如何做到這一點?
僞代碼:c#如何將var與另一個var連接以指向應用程序SettingsName?
using wLog.Properties;
var sName = frmControlProp[cn].SettingName;
var pSettings = Properties.Settings.Default + sName;
SNAME值等於,例如,密碼。我想pSettings等於Properties.Settings.Default.Password
我該如何做到這一點?
Properties.Settings.Default
將返回Properties.Settings
的實例,該實例將是ApplicationSettingsBase
的子類。這與一個string
關鍵的indexer,所以你可以使用:
string name = frmControlProp[cn].SettingName;
object setting = Properties.Settings.Default[name];
需要注意的是,如果你知道(並且希望使用)你有興趣在設定的類型,你需要投。例如:
string setting = (string) Properties.Settings.Default[name];
還要注意的是,如果設置不存在,一個SettingsPropertyNotFoundException
將被拋出。您可以使用PropertyValues
屬性來獲取所有值,並檢查你感興趣的一個存在。
你不能完全按照你想要的來編寫代碼,也沒有語法糖讓你接近想要的語法。
這通常通過使用字典來實現。不知道是什麼類型的Deafult
信息,但假設它是某種IDictionary
代碼是這樣:
var pSettings = Properties.Settings.Default[settingName];
另一種選擇是使用反射和名稱獲取屬性 - 從這個問題Get property value from string using reflection in C#,樣品:
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
var pSettings = (string)GetPropValue(Properties.Settings.Default, settingName);
使用反射
using wLog.Properties;
var sName = frmControlProp[cn].SettingName;
var type = Properties.Settings.Default.GetType();
var pSettings = type.GetField(sName).GetValue(Properties.Settings.Default);
哦,你想要動態獲取該屬性?如果是這樣,你必須使用[反射](http://stackoverflow.com/questions/2762531/c-sharp-reflection-and-getting-properties)。 – glautrou