Can I use reflection to get an existing variable b

2019-08-01 22:10发布

I'm taking over somebody's work and there is a lot of duplicated code. For now, I just want to change the following code: (the code I wanted to change is after this block of code)

        if (Session["opt3PSRAddHrs4"] != null)
        {
            lblDay4AddHrs.Text = "Additional Hours: " + (String)Session["opt3PSRAddHrs4"];
        }
        else
        {
            lblDay4AddHrs.Visible = false;
        }



        if (Session["opt3PSRAddHrs5"] != null)
        {
            lblDay5AddHrs.Text = "Additional Hours: " + (String)Session["opt3PSRAddHrs5"];
        }
        else
        {
            lblDay5AddHrs.Visible = false;
        }

        if (Session["opt3PSRAddHrs6"] != null)
        {
            lblDay6AddHrs.Text = "Additional Hours: " + (String)Session["opt3PSRAddHrs6"];
        }
        else
        {
            lblDay6AddHrs.Visible = false;
        }

        if (Session["opt3PSRAddHrs7"] != null)
        {
            lblDay7AddHrs.Text = "Additional Hours: " + (String)Session["opt3PSRAddHrs7"];
        }
        else
        {
            lblDay7AddHrs.Visible = false;
        }

to

for (int i = 0; i < 7; i++) {

   Label label = Reflection.getVariable(type = "Label", name = "lblDay" + i + "AddHrs");
   string sessionData = (string) Session["opt3PSRAddHrs" + i];
   if ( sessionData != null) {
      label.Text = "Additional Hours: " + sessionData;
   }
   else {
      label.Visible = false;
   }
}

using reflection. Since the name of those labels follow a pattern, can reflection help?

(BTW, perhaps putting all opt3PSRAddHrs stuff in an array is a good idea, but you know, for now I don't want to change that part of code... Every change will probably leave inconsistency...)

1条回答
狗以群分
2楼-- · 2019-08-01 22:30

Reflection isn't the answer. You should use the Page.FindControl method instead.

To find a label at the page level you would use:

Label label = (Label)FindControl("lblDay" + i + "AddHrs");

Note that you'll need to use it on the container which holds your labels. For example, if your labels exist within a Panel with ID="myPanel" you would use myPanel.FindControl(...).

查看更多
登录 后发表回答