我可以使用反射通过提供其名字来获得一个现有的变量? [英] Can I use reflection to get an existing variable by providing its name?

查看:96
本文介绍了我可以使用反射通过提供其名字来获得一个现有的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我接手别人的工作,有很多重复的code的。现在,我只是想更改以下code:(在code我想改变为code的此块之后)

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;
        }

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?

(顺便说一句,也许把所有的东西opt3PSRAddHrs在数组中是个好主意,但你知道,现在我不想改变code的那部分......每一个改变都可能会离开不一致.. 。)

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

推荐答案

反思是不是答案。您应该使用 Page.FindControl 方法,而不是

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");

请注意,你需要使用它持有的标签在容器上。例如,如果一个面板 ID =myPanel存在于您的标签你可以使用 myPanel.FindControl(...)

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

这篇关于我可以使用反射通过提供其名字来获得一个现有的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆