Get dynamic property from Settings

老子叫甜甜 提交于 2019-11-30 03:12:04

问题


I've got a few properties stored in my AppConfig and now I want to access them dynamically (e.g. in a loop or function).

Accessing the values using MySettings.NAME_OF_THAT_THING is no problem, but what if the name is variable?

I tried:

String propertyValue = MySettings.GetType().GetProperty("NAME_OF_THAT_THING").ToString();

But the only thing I got back is the name of the property. How can I do this?


回答1:


String propertyValue = MySettings.GetType()
.GetProperty("NAME_OF_THAT_THING")
.GetValue(MySettings, null); //replace MySettings with null in GetValue(...) if MySettings is  a static class



回答2:


All you need to do is:

String propertyValue = Settings.Default["NAME_OF_THAT_THING"].ToString();

While using reflection will obviously work, it's overkill.




回答3:


Have you tried using the ConfigurationManager.AppSettings property? You should be able to get your setting via the following code:

String propertyValue = ConfigurationManager.AppSettings["NAME_OF_THAT_THING"];

The MSDN article for ConfigurationManager.AppSettings also includes an example for looping through all of the entries in AppSettings by index, rather than name.




回答4:


answer to the orginal poster question would be like: MySettings[NAME_OF_THAT_THINGmysettings] does the job like previous post

however for those people looking for answer to using the builtin settings in their windows app: myAppDefaultNameSpace.Properties.Settings.Default[NAME_OF_THAT_THINGmysettings] is the way to go



来源:https://stackoverflow.com/questions/10996980/get-dynamic-property-from-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!