Get static field value

I have the following class:

public static class Pages
{
    public static string LoggedOut = "LoggedOut.aspx";
    public static string Login = "Login.aspx";
    public static string Home = "Home.aspx";
}

I know that I can use Pages.Homestatically, but there is a reason for my question.

I want to have a method that I can name as follows:

string pageName = Pages.GetPage("Home");

and etc.

C'est maybe?

Thanks Dave

+5
source share
4 answers

You can use the following:

var field = typeof(Pages).GetField("Home", BindingFlags.Public | BindingFlags.Static);
var value = (string)field.GetValue(null);
+16
source

You can do this, as Conrad suggested using reflection. But I would find it much better to use a dictionary and not rely on reflection for such a task.

public static class Pages
{
    private static readonly IDictionary<String, String> PageMap = null;

    private static Pages()
    {
        Pages.PageMap = new Dictionary<String, String>();

        Pages.PageMap.Add("LoggedOut", "LoggedOut.aspx");
        Pages.PageMap.Add("Login", "Login.aspx");
        Pages.PageMap.Add("Home", "Home.aspx");
    }

    public static GetPage(String pageCode)
    {
        String page;
        if (Pages.PageMap.TryGet(pageCode, out page)
        {
            return page;
        }
        else
        {
            throw new ArgumentException("Page code not found.");
        }
    }
}

You must, of course, configure error handling to your actual requirements.

+4
source

tuppence... ( "" ), const, .. Pages.Home ( , , ). , :

string s = ...something clever...
string page = GetPage(s);

const, , :

string s = ...something clever...
FieldInfo field = typeof(Pages).GetField(s,
     BindingFlags.Static | BindingFlags.Public);
string page = (string)field.GetValue(null);

, .

+1

, . , , ( )

    public enum pages { LoggedOut, Login, Home }

    static Dictionary<pages, string> pageDict = new Dictionary<pages, string>() {
        {pages.Home, "Home.aspx"},
        {pages.Login, "Login.aspx"},
        {pages.LoggedOut, "LoggedOut.aspx"}
    };

    public static string getPage(pages pageName)
    {
        return pageDict[pageName];
    }
0

All Articles