使用变量引用对象(c#)

时间:2017-11-24 16:46:21

标签: c#

我一直在做一个需要在执行期间更改对象属性的程序。为了让我能够轻松管理,我保留了原始对象名称,即" button1"

我的问题是,是否有办法通过变量引用对象名称来改变循环

我必须写一些像

这样的东西
private void disable ()
{
    this.button1.Visible = false;
    this.button2.Visible = false;
    this.button3.Visible = false;
    //...
}

我尝试过像

这样的事情
int a;
for(a=1;a==50;a++)
{
    this.buttona.Visible =false;
}

显然不起作用

那么有没有办法可以用变量引用对象?

先谢谢

2 个答案:

答案 0 :(得分:5)

您可以使用此代码:

        foreach (var c in this.Controls)
        {
            if (c is Button button)
                button.Visible = false;
        }

或者这个:

        for (int i = 0; i < 50; i++)
        {
            var c = this.Controls["button" + i];
            (c as Button).Visible = false;
        }

答案 1 :(得分:0)

如果您没有使用UWP,WPF等,这可能不起作用。 如果你正在做UWP,WPF等,这可能会有所帮助。由于所有这些按钮都属于一个面板(我假设如此),面板的子节点或内容应该是context semiring_1 begin definition scale :: "nat ⇒ 'a ⇒ 'a" where "scale n = times (of_nat n)" lemma [simp]: "scale 0 a = 0" "scale (Suc n) a = a + scale n a" by (simp_all add: scale_def algebra_simps) lemma "((plus a) ^^ n) 0 = scale n a" by (induct n) (simp_all) end 对象,可以由IEnumerable循环处理。例如,如果我有以下XAML代码:

foreach

我可以使用以下方法遍历按钮:

<Grid x:Name="myGrid">
    <Button x:Name="Button1" Tag="myButton1"/>
    <Button x:Name="Button2" Tag="myButton2"/>
    <!-- ... -->
</Grid>