C# Dynamically Get Variable Names and Values in a Class

时光怂恿深爱的人放手 提交于 2019-12-07 14:20:18

问题


I am currently making a program (C# .Net 4) that has multiple options, which are saved to a file.

These options are their own variables in-code, and I was wondering if there was a way to get the variables and values of these options dynamically in code.

In my case, I have these options in a "Settings" class, and I access them from my main form class using Settings.varSetting.

I get and set these variables in multiple places in code; is it possible to consolidate the list of variables so that I can access and set them (for example, creating a Settings form which pulls the available options and their values and draws the form dynamically) more easily/consistently?

Here are the current variables I have in the Settings class:

    public static Uri uriHomePage = new Uri("http://www.google.com");
    public static int intInitOpacity = 100;
    public static string strWindowTitle = "OpaciBrowser";
    public static bool boolSaveHistory = false;
    public static bool boolAutoRemoveTask = true; //Automatically remove window from task bar if under:
    public static int intRemoveTaskLevel = 50; //percent
    public static bool boolHideOnMinimized = true;

Thanks for any help,

Karl Tatom ( TheMusiKid )


回答1:


var dict = typeof(Settings)
    .GetFields(BindingFlags.Static | BindingFlags.Public)
    .ToDictionary(f=>f.Name, f=>f.GetValue(null));



回答2:


You might want to consider using the Application Settings features built into the framework for loading and storing application settings.




回答3:


read about reflections: http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.100%29.aspx



来源:https://stackoverflow.com/questions/12251910/c-sharp-dynamically-get-variable-names-and-values-in-a-class

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