Get dynamic property in settings

I have several properties stored in my AppConfig, and now I want to access them dynamically (for example, in a loop or function).

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

I tried:

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

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

+6
source share
4 answers
 String propertyValue = MySettings.GetType() .GetProperty("NAME_OF_THAT_THING") .GetValue(MySettings, null); //replace MySettings with null in GetValue(...) if MySettings is a static class 
+5
source

All you have to do is:

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

While using reflection will obviously work, it will be redundant.

+8
source

Have you tried to use the ConfigurationManager.AppSettings property? You can get the settings through the following code:

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

The MSDN article for ConfigurationManager.AppSettings also provides an example for cycling through all elements in AppSettings by index rather than name.

0
source

the answer to the original bed question would look like this: MySettings [NAME_OF_THAT_THINGmysettings] is completing a task similar to the previous message

however, for those looking for an answer to using the built-in settings in their Windows application: myAppDefaultNameSpace.Properties.Settings.Default [NAME_OF_THAT_THINGmysettings] is the way to go

0
source

Source: https://habr.com/ru/post/917887/


All Articles