开发者

Can I use reflection to get an existing variable by providing its name?

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...)


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(...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜